對於這種情況,您可以使用@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