我有这个 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...}
我想知道,为什么它使用带有 3 个参数的 Label
构造函数,而不是带有 2 个参数?
最佳答案
我认为它根本不会调用 3-arg 构造函数。它怎么知道什么是什么?相反,它调用无参数构造函数并设置字段值。
如果您希望它调用特定的构造函数,请使用@JsonCreator
注释。请注意,您只能将其设置在一个上。
有关详细信息,请参阅此答案:
How to deserialize a class with overloaded constructors using JsonCreator
关于java - JSON Jackson 根据我的预期映射到其他构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40995609/