2014-10-31 50 views
0

問題1問題:
兩個約JsonProperty

class Point { 
    private int x; 
    private int y; 
    @JsonCreator 
    public Point(@JsonProperty("x") int x, @JsonProperty("y") int y) { 
     this.x = x; 
     this.y = y; 
    } 
} 

class Point { 
    @JsonProperty("x") 
    private int x; 
    @JsonProperty("y") 
    private int y; 
    @JsonCreator 
    public Point(int x, int y) { 
     this.x = x; 
     this.y = y; 
    } 
} 

等同?

問題2:
如果我有沒有出現在構造函數的參數,如字段:

class Point { 
    private int x; 
    private int y; 
    private int z; 
    @JsonCreator 
    public Point(@JsonProperty("x") int x, @JsonProperty("y") int y) { 
     this.x = x; 
     this.y = y; 
     z = 0; 
    } 
} 

不傑克遜仍然知道那場(z)和它的價值?

+0

1.不,可能它們不相同。第一個是要走的路。第二種情況需要默認的構造函數,因爲Jackson似乎並不試圖從參數名稱中猜出字段名稱。 – user3159253 2014-10-31 15:10:41

+0

2.使用默認設置Jackson簡單地忽略所有私人字段。 – user3159253 2014-10-31 15:11:23

回答

0

爲了序列化/反序列化類的私人領域,沒有正式的getter/setter方法,我必須做到以下幾點:

mapper.enable(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS); 
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); 

,也定義了私人默認構造我的課,像這樣:

public class ElementDesc { 
    @SuppressWarnings("unused") 
    private ElementDesc() { this(null, null, false); } 

    public ElementDesc(/* a regular constructor with parameters etc */) { 
    ... 
    } 

    private final String field1; 
    private final String field2; 
    private final boolean field3; 
} 

在這種情況下,Jackson可以成功地序列化/反序列化無需使用常規構造函數和(訪問器)方法(如果有)的類的實例。