Hanzala Jamash
Hanzala Jamash

Reputation: 29

Deserialize json using jackson to map fields to a wrapper class

I have a JSON that looks like this

  {
     Name: "Jhon",
     Age: 28,
     Children:[{..},{..}]
}

I have created two entities Person and Children, and a wrapper Payload

class Payload{
  Person A;
  Children x[];
}

I want to do something like this

Payload payload = mapper.readValue(request, Payload.class);

The fields are not being mapped correctly, since name and age fields are at root. A JSON like below would have worked in this scenario but I cannot change the JSON neither can I place the name and age fields inside Payload. I find out about @JsonRootName annotation but not sure how or will it work or not.

{
    Person: { Name: "Jhon", Age:28},
    Children: [{..},{..}]
}

Upvotes: 0

Views: 1257

Answers (2)

oktaykcr
oktaykcr

Reputation: 376

You can use Json To Java Class.

// import com.fasterxml.jackson.databind.ObjectMapper; // version 2.11.1
// import com.fasterxml.jackson.annotation.JsonProperty; // version 2.11.1
/* ObjectMapper om = new ObjectMapper();
Payload payload = om.readValue(myJsonString), Payload.class); */
public class Payload {

    @JsonProperty("Name") 
    public String name;

    @JsonProperty("Age") 
    public int age;

    @JsonProperty("Children") 
    public List<Children> children;
}

Upvotes: 1

Kaj Hejer
Kaj Hejer

Reputation: 1040

To have name and age on top level in the jsonc-ode you might want to try putting the attributes at top level of your Payload class:

class Payload{
  String name;
  int age;
  Children x[];
}

Please let me know if this is helpful.

Upvotes: 0

Related Questions