2016-12-06 32 views
0

我有這樣的JSON:JSON傑克遜映射到其他構造從我所期待的

{ 
    "label":{  
      "label":"1D812", 
      "version":"01" 
      },  
    "productionDate":"140415", 
    "boxNumber":"003", 
    "quantity":11000, 
    "order":"0000", 
    "documentId":"DOC-HHS", 
    "location":1 
} 

和我運行以下命令來創建一個Box對象

ObjectMapper mapper = new ObjectMapper(); 
Box box = mapper.readValue(myJSON, Box.class); 

Box類有以下構造函數:

public Box(Label label, String productionDate, String boxNumber, int quantity, String order, String documentId,int location) { 
    this.label = label; 
    this.quantity = quantity; 
    this.order = order; 
    this.boxNumber = boxNumber; 
    this.location = location; 
    this.documentId = documentId; 
    this.productionDate = productionDate; 
} 

而在Label級我有這些構造函數(按順序,如果它的事項)

public Label() { 
}  

public Label(String label) { 
     this.label = label; 
} 

public Label(String label, String version) { 
    this.label = label; 
    this.version = version; 
} 

public Label(String label, String version, SupplierL supplier) { 
    this.label = label; 
    this.version = version; 
    this.supplier = supplier; 
    this.labelWithVersion = label + "-" + version; 
} 

當我System.out.println(box.toString());我看到:

Box{label=Label{label=1D812, version=01, supplier=null}, etc...} 

我很納悶,爲什麼它使用的Label構造與3個參數而不是2?

+0

我剛剛意識到'的System.out.println(box.toString()); '打印'toString()'參數的含義。凡在我的情況下,它'@覆蓋 公共字符串的ToString(){ 回報 「標籤{」 + 「標籤=」 +標籤+ 「版本=」 +版本+ 「供應商=」 +供應商+ '}'; }'..我卡住了一會兒...... – yaylitzis

回答

1

我不認爲它調用了3參數的構造函數的。它怎麼會知道什麼是什麼?相反,它調用無參數構造函數並設置字段值。

如果你想它來調用特定的構造,使用@JsonCreator註解。請注意,您只能將其設置爲一個。

看到這個答案的詳細信息:

How to deserialize a class with overloaded constructors using JsonCreator

+0

你是對的。我被卡住了一會兒 'System.out.println'打印什麼'tostring()'作爲參數 – yaylitzis

0

有一個在你的JSON對象中沒有供應商。因此,正確地將使用2參數的構造函數:

"label":{  
     "label":"1D812", 
     "version":"01" 
     }  

而這正是你在輸出中看到:

label=Label{label=1D812, version=01, supplier=null}