我有这个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 :(得分:1)
我根本不认为它会调用3-arg构造函数。怎么会知道什么是什么?相反,它调用no-args构造函数并设置字段值。
如果您希望它调用特定的构造函数,请使用@JsonCreator
注释。请注意,您只能将其设置为一个。
有关详细信息,请参阅此答案:
How to deserialize a class with overloaded constructors using JsonCreator
答案 1 :(得分:0)
您的JSON对象中没有供应商。所以它恰当地使用了2个参数构造函数:
"label":{
"label":"1D812",
"version":"01"
}
这正是你在输出中看到的:
label=Label{label=1D812, version=01, supplier=null}