2016-12-05 45 views
0

假設我有一個父母子女關係。我的父母JSON看起來像傑克遜可以處理中間關係

{ 
    childrens: [...] 
} 

比方說,我想模型(德)序列化到/從有家長和孩子之間的中間對象。

class Parent { 
    Intermediate intermediate 
} 

class Intermediate { 
    Child[] children; 
} 

我可以配置傑克遜反序列化JSON轉換成模型時創建的中間對象和序列化回JSON時同樣跳過中間目標?

+0

我不相信這是可以做到無需編寫[自定義反序列化程序](http://www.baeldung.com/jackson-deserialization)(和序列化程序)。 – rmlan

+0

@rmlan如果我的問題中的模型真的處在一個更大的模型樹的中間,那麼定製解串器是否需要處理該模型樹中的所有其他內容?或者我可以限制它,所以我只需要在父/中/小孩周圍編寫自定義代碼? – hvgotcodes

+0

您應該能夠在字段本身上使用@JsonDeserialize(using = CustomDeserializer.class)(和@JsonSerialize)批註,而無需處理整個對象。 [看到這個問題](http://stackoverflow.com/questions/5269637/custom-deserialization-of-json-field-with-jackson-in-java) – rmlan

回答

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.