简体   繁体   中英

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: [{..},{..}]
}

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM