杰克逊可以处理中间关系

时间:2016-12-05 21:37:17

标签: java json jackson

我们说我有亲子关系。我的父亲json看起来像

{
   childrens: [...]
}

让我们说我想(de)序列化到/从的模型在父和子之间有一个中间对象。

class Parent {
   Intermediate intermediate
}

class Intermediate {
   Child[] children;
}

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

1 个答案:

答案 0 :(得分:1)

您可以对此案例使用@JsonUnwrapped注释。这是一个与帖子具有相似结构的示例

<强> 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.