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

com.fasterxml.jackson.databind.JsonMappingException: no suitable constructor found, can not deserialize from Object value

我在映射响应时遇到标题错误: 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 information?)
 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
    }
]

}

添加注释 @NoArgsConstructor@AllArgsConstructor

objectmapper首先调用默认构造函数创建POJO实例。然后 JSON 中的每个条目都被解析并使用设置器在实例中设置。由于您没有默认构造函数,因此它失败并出现适当的异常。 @NoArgsConstructor 注解提供了默认的构造函数,它使它工作。

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

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

请注意,我将 @NoArgsConstructor 添加到 class。