imbond imbond - 6 months ago 34
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.


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);