【问题标题】:Can Jackson deal with intermediate relationships杰克逊可以处理中间关系吗
【发布时间】:2017-04-20 09:51:20
【问题描述】:

假设我有亲子关系。我的父 json 看起来像

{
   childrens: [...]
}

假设我想要(反)序列化到/从的模型在父级和子级之间有一个中间对象。

class Parent {
   Intermediate intermediate
}

class Intermediate {
   Child[] children;
}

我可以配置 Jackson 在将 json 反序列化为模型时创建该中间对象,并在序列化回 json 时类似地跳过中间对象吗?

【问题讨论】:

  • 如果不为 Parent 编写 custom deserializer(和序列化程序),我不相信这可以做到。
  • @rmlan 如果我的问题中的模型确实位于更大的模型树的中间,那么自定义反序列化器是否需要处理该模型树中的所有其他内容?或者我可以限制它,所以我只需要围绕 Parent/Intermediate/Child 编写自定义代码?
  • 您应该能够在字段本身上使用@JsonDeserialize(using = CustomDeserializer.class)(和@JsonSerialize)注释,而无需处理整个对象。 See this question
  • 我不知道 JsonUnwrapped。根据文档,这实际上应该可以解决问题。
  • 据我所知,@JsonUnwrapped 不适用于列表。

标签: java json jackson


【解决方案1】:

您可以在这种情况下使用@JsonUnwrappedannotation。这是一个与您的帖子结构相似的示例

Parent.java

import com.fasterxml.jackson.annotation.JsonUnwrapped;

public class Parent {

    @JsonUnwrapped
    private Intermediate intermediate;

    public Intermediate getIntermediate() {
        return intermediate;
    }

    public void setIntermediate(Intermediate intermediate) {
        this.intermediate = intermediate;
    }
}

Intermediate.java

public class Intermediate {
    private Child[] children;

    public Child[] getChildren() {
        return children;
    }

    public void setChildren(Child[] children) {
        this.children = children;
    }
}

Child.java

public class Child {
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

示例文档

{
  "children": [
    {
      "name": "Foo",
      "age": 20
    },
    {
      "name": "Bar",
      "age": 22
    }
  ]  
}

测试驱动程序

ObjectMapper mapper = new ObjectMapper();
Parent parent = mapper.readValue(json, Parent.class);

for (Child child : parent.getIntermediate().getChildren()) {
    System.out.println("Child: " + child.getName() + " is " + child.getAge() + " years old.");
}

产生以下输出:

Child: Foo is 20 years old.
Child: Bar is 22 years old.

【讨论】:

    猜你喜欢
    • 2017-06-14
    • 2013-04-11
    • 2012-09-13
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2012-07-21
    • 2015-01-24
    • 1970-01-01
    相关资源
    最近更新 更多