imbond imbond - 1 month ago 9
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;

@Id
@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

You need create class contain list and use ResponseEntity.

public class Foo {

  private List<Country> countries;

  // get/set...
}

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

        Country country = new Country();

        foo.getCountries().add(country);

        return ResponseEntity.ok(foo);
    }
}