简体   繁体   English

使用 jackson 将 json 反序列化到 map 字段到包装器 ZA2F2ED4F8EBC2CBB1DDDDZAB0

[英]Deserialize json using jackson to map fields to a wrapper class

I have a JSON that looks like this我有一个看起来像这样的 JSON

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

I have created two entities Person and Children, and a wrapper Payload我创建了两个实体 Person 和 Children,以及一个包装 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.像下面这样的 JSON 可以在这种情况下工作,但我无法更改 JSON 也不能将名称和年龄字段放在 Payload 中。 I find out about @JsonRootName annotation but not sure how or will it work or not.我发现了 @JsonRootName 注释,但不确定它是如何工作的或是否会工作。

{
    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:要将nameage放在 jsonc-ode 的顶层,您可能需要尝试将属性放在 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 .您可以使用Json 到 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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