com.fasterxml.jackson.databind.JsonMappingException:找不到合适的构造函数,无法从Object值反序列化

问题描述

映射响应时出现标题错误: Retention.java

@Getter
@Setter
@Builder
public class Retention {
    private int min_age_days;
    private int max_age_days;
    private boolean auto_prune;
}

我正在使用Java +龙目岛

完整的堆栈跟踪:

com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of getChannelInfo.Retention: no suitable constructor found,can not deserialize from Object value (missing default constructor or creator,or perhaps need to add/enable type @R_186_4045@ion?)
 at [Source: {"id":"53","href":"https://<ip address:port>/api/v1/channel/53","public_read":true,"public_write":true,"sequenced":true,"locked":false,"head":0,"retention":{"min_age_days":0,"max_age_days":0,"auto_prune":true},"access_tokens":[{"id":"58","token":"","description":"Owner","can_read":true,"can_write":true}]}; line: 1,column: 160] (through reference chain: service.xxxx["retention"])

我的JSON如下所示:

{
"id": "53","href": "https://161.35.164.133:5011/api/v1/channel/53","public_read": true,"public_write": true,"sequenced": true,"locked": false,"head": 0,"retention": {
    "min_age_days": 0,"max_age_days": 0,"auto_prune": true
},"access_tokens": [
    {
        "id": "58","token": "DAH-9_5dwid6PIBjtHjBdl3PwTVD3qh53ZWddSCfw-eQOyY4MRyR8ZolmARU2q2lGyoN7oD74cwWQHHANkJDAw","description": "Owner","can_read": true,"can_write": true
    }
]

}

解决方法

您需要为该类定义一个构造函数。

@Getter
@Setter
@Builder
@NoArgsConstructor
public class Retention {
    private int min_age_days;
    private int max_age_days;
    private boolean auto_prune;
}

请注意,我在类中添加了@NoArgsConstructor。

,

添加注释@NoArgsConstructor@AllArgsConstructor

objectmapper首先调用默认构造函数以创建POJO的实例。然后,将解析来自JSON的每个条目,并使用setter在实例中对其进行设置。由于您没有默认的构造函数,因此它会失败,并带有适当的异常。 @NoArgsConstructor注释提供了默认的构造函数,并使它可以工作。