无法从 Object 值(无委托或基于属性的创建者)反序列化,即使存在默认构造函数

我有一个类,看起来像

class MyClass {
    private byte[] payload;

    public MyClass(){}

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

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

}

我正在使用Jackson,所以序列化,然后去反序列化。序列化工作正常,但在反序列化期间,我收到此错误消息 -

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

我在网上阅读了这个问题,并遇到了几个文本,建议使用默认构造函数或带有注释的构造函数。我尝试添加两者,但仍然得到这个例外。我在这里错过了什么?@JsonCreator


答案 1

编辑:

我刚刚找到了一个更好的解决方案,将ParanamerModule添加到:ObjectMapper

mapper.registerModule(new ParanamerModule());

专家:

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

ParameterNamesModule 相比,其优点似乎是不需要使用参数编译类。-parameters

结束编辑


在Jackson 2.9.9中,我试图反序列化这个简单的POJO,并出现了相同的异常,添加一个默认构造函数解决了这个问题:

POJO:

public class Operator {

    private String operator;

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

    public String getOperator() {
        return operator;
    }
}

ObjectMapper 和 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"}

例外:

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]

解决方案(带有默认构造函数的 POJO):

public class Operator {

    private String operator;

    private Operator() {
    }

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

    public String getOperator() {
        return operator;
    }
}

答案 2

我观察到了同样的问题。我的问题是由于我使用了错误的JsonCreator类型引起的。我错误地使用了org.codehaus.jackson.annotate.JsonCreator,但应该使用com.fasterxml.jackson.annotation.JsonCreator