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

时间:2018-10-08 19:20:05

标签: java jackson

我有一个看起来像的课程

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批注的构造函数的文本。我尝试将两者都添加,但仍然遇到该异常。我在这里想念什么?

3 个答案:

答案 0 :(得分: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参数编译类。

END EDIT

在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和序列化/反序列化:

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;
    }
}

答案 1 :(得分:0)

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

答案 2 :(得分:0)

在子类对象中添加默认构造函数:

public NameOfClass() {
    super();
}