imbond imbond - 1 year ago 98
Java Question

How to display class as a JSON response in Java?

Currently I'm working on spring project and I want to display class as a JSON response. Following is the class template and other related details.

public class Country {

@Column(name = "name")
private String name;

@Column(name = "code")
private String Code;

//Getters & Setters ...

current response :

[{"name":"Andorra","code":"AD"},{"name":"United Arab Emirates","code":"AE"}]

Expected response :

[ { "countries" : [{"name":"Andorra","code":"AD"},{"name":"United Arab Emirates","code":"AE"}], "status" : "ok", "message":"success", etc..etc...}]

instead of status and message, it could be some array list too.

Answer Source

You need create class contain list and use ResponseEntity.

public class Foo {

  private List<Country> countries;

  // get/set...

public class MyController {
    @RequestMapping(value = "/foo", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
    public ResponseEntity<Foo> foo() {
        Foo foo = new Foo();

        Country country = new Country();


        return ResponseEntity.ok(foo);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download