cannot deserialize from Object value (no delegate- or property-based Creator) even with default constructor present

nishant picture nishant · Oct 8, 2018 · Viewed 29.6k times · Source

I have a class that looks like

class MyClass {
    private byte[] payload;

    public MyClass(){}

    @JsonCreator
    public MyClass(@JsonProperty("payload") final byte[] payload) {
        this.payload = payload;
    }

    public byte[] getPayload() {
        return this.payload;
    }

}

I am using Jackson so serialize and then to deserialize. Serialization works fine, but during deserialization, I am getting this error message -

Cannot construct instance of `mypackage.MyClass` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)

I was reading about this problem online, and came across several texts recommending to have a default constructor or a constructor with @JsonCreator annotation. I tried adding both, but still getting that exception. What am I missing here?

Answer

flavio.donze picture flavio.donze · Aug 26, 2019

EDIT:

I just found a much better solution, add the ParanamerModule to the ObjectMapper:

mapper.registerModule(new ParanamerModule());

Maven:

<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-paranamer</artifactId>
    <version>${jackson.version}</version>
</dependency>

The advantage against the ParameterNamesModule seems to be that the classes do not need to be compiled with the -parameters argument.

END EDIT


With Jackson 2.9.9 I tried to deserialize this simple POJO and came accros the same exception, adding a default constructor solved the problem:

POJO:

public class Operator {

    private String operator;

    public Operator(String operator) {
        this.operator = operator;
    }

    public String getOperator() {
        return operator;
    }
}

ObjectMapper and Serialize/Deserialize:

ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
mapper.setVisibility(PropertyAccessor.CREATOR, Visibility.ANY);

String value = mapper.writeValueAsString(new Operator("test"));
Operator result = mapper.readValue(value, Operator.class);

JSON:

{"operator":"test"}

Exception:

com.fasterxml.jackson.databind.exc.MismatchedInputException: 
Cannot construct instance of `...Operator` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (String)"{"operator":"test"}"; line: 1, column: 2]

Solution (POJO with default constructor):

public class Operator {

    private String operator;

    private Operator() {
    }

    public Operator(String operator) {
        this();
        this.operator = operator;
    }

    public String getOperator() {
        return operator;
    }
}