编辑:
我刚刚找到了一个更好的解决方案,将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;
}
}