gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:35:21 26 4
gpt4 key购买 nike

我有一个类看起来像

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 注释的构造函数的文本。我尝试同时添加两者,但仍然出现该异常。我在这里缺少什么?

最佳答案

编辑:

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

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

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

关于java - 即使存在默认构造函数,也无法从对象值反序列化(没有基于委托(delegate)或属性的创建者),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52708773/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com