hugodesmarques hugodesmarques - 1 year ago 66
Java Question

Map Java field to JSON document root

I couldn't find an example how to map the following json:


To the following java object using jackson:

public class EntityDto {
private Map<String, Object> content;

Notice the dto is just a wrapper. What I'm trying to achieve is to have an object EntityDto with a Map{name=>"hugodesmarques", age=>30, id=>1}.

I want to avoid having to map each json field to an object map.

Answer Source

A step back

First of all, the JSON you posted in you question is invalid: there's a comma after 30 and it shouldn't be there. Fix your JSON otherwise Jackson won't parse it:

  "id": 1,
  "name": "hugodesmarques",
  "age": 30

Parsing the JSON

Add a constructor annotated with @JsonCreator to the EntityDto class, as following:

public class EntityDto {

    private Map<String, Object> content;

    public EntityDto(Map<String, Object> content) {
        this.content = content;

    // Getters and setters omitted

Then parse the JSON using ObjectMapper:

String json = "{\"id\":1,\"name\":\"hugodesmarques\",\"age\":30}";

ObjectMapper mapper = new ObjectMapper();
EntityDto entityDto = mapper.readValue(json, EntityDto.class);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download