imbond
imbond

Reputation: 2098

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.

Upvotes: 3

Views: 2728

Answers (3)

FatherMathew
FatherMathew

Reputation: 990

Actually you can also achieve using jackson library.

//Create obj of ObjectMapper

ObjectMapper mapper = new ObjectMapper();

//Get the Json string value from the mapper

String json = mapper.writeValueAsString(obj)  

And then return this json string in your controller method.

The advantage of using this is that, you can also ignore certain fields in the POJO for JSON conversion using @JsonIgnore annotation (Put this annotation before the getter of the field that you want to ignore) (Not sure if you can do the same from Spring ResponseEntity.

Note: Please correct me if I am wrong anywhere.

Upvotes: 0

Funzzy
Funzzy

Reputation: 178

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

Upvotes: 2

Thomas Weglinski
Thomas Weglinski

Reputation: 1094

You should create another object, e.g. called Countries as shown below:

public class Countries {
    private List<Country> countries;

    // getters & setters
}

or:

public class Countries {
    private Country[] countries;

    // getters & setters
}

The list or array of Country objects will map to your expected {"countries" : [{"name":"Andorra","code":"AD"},{"name":"United Arab Emirates","code":"AE"}]}, because the JSON {} refers to some object and [] refers to list/array in Java code.

Upvotes: 0

Related Questions