java - JSON Jackson 根据我的预期映射到其他构造函数

标签 java json jackson

我有这个 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/

相关文章:

java - 无法使用 Java 在 MongoDB 中上传 JSON

java - 在@RequestBody 中使用 spring 转换器

java - 使用 Jackson 反序列化接口(interface),其中接口(interface)实现在序列化对象中指定

java - 用 Jackson 解析巨大的 JSON

java - 缓存标注信息的 map 是否需要同步?

java - 将 Button OnClick 与 Fragment 中 RecyclerView 内的 Row OnClick 分开

Python 请求 : Post JSON and file in single request

json - shell 脚本解析问题 : unexpected INVALID_CHARACTER (Windows cmd shell quoting issues? )

java - 将正则表达式转换为 java 兼容正则表达式的简单方法?

java - 跨线程访问变量和方法