我有一个看起来像的类class MyClass { private byte[] payload; public MyClass(){} @JsonCreator public MyClass(@JsonProperty(\'payload\') final byte[] payload) { this.
我有一堂课看起来像
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
注释的构造函数。我尝试添加两者,但仍然出现该异常。我这里遗漏了什么?
编辑:
我刚刚找到了一个更好的解决方案,将 ParanamerModule 到 ObjectMapper
:
mapper.registerModule(new ParanamerModule());
Maven:
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-paranamer</artifactId>
<version>${jackson.version}</version>
</dependency>
的优势 ParameterNamesModule 似乎在于类不需要用参数进行编译 -parameters
。
结束编辑
使用 Jackson 2.9.9,我尝试反序列化这个简单的 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;
}
}