2014-09-29 63 views
0

實例化新對象,我想從使用傑克遜以下結構的JSON字符串創建一個對象如何防止傑克遜在反序列化

public class A { 
    private int id; 
    private B b; 

    public A() { 
     id = 5; 
     b = new B(10, 20); 
    } 

    public int getId() { 
     return this.id; 
    } 

    public B getB() { 
     return b; 
    } 
} 
public class B { 
    private int first; 
    private int last; 

    public B(int first, int last) { 
     this.first = first; 
     this.last = last; 
    } 
} 

如果我使用下面的代碼序列化/反序列化它在反序列化的步驟失敗 注意:我不想更改代碼結構併爲類B添加默認的空構造函數或使用JsonProperty註釋。因爲A類負責內我需要一些方法來防止傑克遜從實例化一個新型B級覆蓋A和B屬性來創建B時的它試圖從JSON字符串

A a = new A(); 
    ObjectMapper b = new ObjectMapper(); 
    b.configure(Feature.FAIL_ON_EMPTY_BEANS, false); 
    String jsonString = b.writeValueAsString(a); 
    // jsonString = {"id":5,"b":{}} which is desirable in serialization but it fails in deserialization with the following statement. 
    A readValue = b.readValue(jsonString, A.class); 

回答

1

@JsonIgnore反序列化A級到您的私人B類變量。

IE:

@JsonIgnore 
private B b;