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

Viewed 2658

I'm getting the Title error while mapping the response: Retention.java

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

I'm using Java + lombok

Full stacktrace:

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"])

My JSON looks like below:

{
"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
    }
]

}

2 Answers

You need to define a constructor to the class.

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

Notice that I added @NoArgsConstructor to the class.

Add annotations @NoArgsConstructor and @AllArgsConstructor

objectmapper calls the default constructor to create the instance of the POJO first. Then each entry from the JSON is parsed and set in the instance using setters. Since you didn't have the default constructor, it failed with an appropriate exception. @NoArgsConstructor annotation provides the default constructor and it makes it work.

Related