对于这种情况,您可以使用@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.
我不相信这是可以做到无需编写[自定义反序列化程序](http://www.baeldung.com/jackson-deserialization)(和序列化程序)。 – rmlan
@rmlan如果我的问题中的模型真的处在一个更大的模型树的中间,那么定制解串器是否需要处理该模型树中的所有其他内容?或者我可以限制它,所以我只需要在父/中/小孩周围编写自定义代码? – hvgotcodes
您应该能够在字段本身上使用@JsonDeserialize(using = CustomDeserializer.class)(和@JsonSerialize)批注,而无需处理整个对象。 [看到这个问题](http://stackoverflow.com/questions/5269637/custom-deserialization-of-json-field-with-jackson-in-java) – rmlan