【问题标题】:Query about flattening a nested json using Jackson关于使用 Jackson 展平嵌套 json 的查询
【发布时间】:2021-02-12 08:35:25
【问题描述】:

我有一个json

{
    "parentId": "123",
    "parentName": "abc",
    "child": {
        "childId": "456",
        "childName": "xyz",
    }  
}

我的要求是将 json 展平,以便我可以将其映射到 pojo

class MyJson{
     private String parentId;
     private String parentName;
     private String childId;

    @JsonCreator
    public MyJson(@JsonProperty("parentId"),@JsonProperty("parentName"),
                      @JsonProperty("childId")){
        this.parentId = parentId;
        this.parentName = parentName;
        this.childId = childId;
    }
}

我知道我总是可以为子对象创建另一个 pojo,但我想知道有没有办法将嵌套的子属性直接映射到 pojo?

【问题讨论】:

标签: spring jackson jackson-databind jackson2


【解决方案1】:

child 是JSON Object,您需要将其声明为Map:

class MyJson {
    private String parentId;
    private String parentName;
    private String childId;

    @JsonCreator
    public MyJson(@JsonProperty("parentId") String parentId,
                  @JsonProperty("parentName") String parentName,
                  @JsonProperty("child") Map<String, String> child) {
        this.parentId = parentId;
        this.parentName = parentName;
        this.childId = child.get("childId");
    }
}

【讨论】:

  • 感谢您的简化回答。这就是我想要的
猜你喜欢
  • 2016-09-29
  • 2019-02-12
  • 2016-10-06
  • 2021-09-05
  • 1970-01-01
  • 2019-12-10
  • 2019-01-26
相关资源
最近更新 更多