gpt4 book ai didi

java - 使用 Jackson 进行 JSON 反序列化 : No suitable constructor found for type - providing default constructor or annotate constructor is imposible

转载 作者:行者123 更新时间:2023-12-01 18:15:15 26 4
gpt4 key购买 nike

我使用 Jackson ObjectMapper 将对象层次结构序列化为 json 字符串。之后我想将对象反序列化回来。我遇到了如下异常。

重要的是 APINewDealArrangementImpl类层次结构超出了我的更改范围 - 它是外部库的一部分。在这种情况下,我无法实现默认构造函数,也无法使用 @JsonCreator注释。

如何避免“找不到合适的构造函数”异常?是否可以使用一些自定义来克服这个问题TypeResolverBuilder Jackson API 中的实现或其他功能?感谢您的帮助。

org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class com.tzero.api.transactions.TransactionState]: can not instantiate from JSON object (need to add/enable type information?)
at [Source: java.io.StringReader@57ac3379; line: 4, column: 5] (through reference chain: com.tzero.api.java.transactions.APINewDealArrangementImpl["state"])
at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObjectUsingNonDefault(BeanDeserializer.java:746)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:683)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:299)
at org.codehaus.jackson.map.deser.SettableBeanProperty$MethodProperty.deserializeAndSet(SettableBeanProperty.java:414)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:697)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2732)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1863)

最佳答案

您可以使用“mixin”在不同类上提供注释。这有点奇怪,但非常有用。

@Test
public void mixin_to_specify_creator() throws Exception {
TargetData target = mapper.addMixIn(TargetData.class, TargetDataMixin.class).reader(TargetData.class)
.<TargetData> readValue("{\"name\":\"the name\", \"description\":\"the description\"}");
assertThat(target.name, equalTo("the name"));
assertThat(target.description, equalTo("the description"));
}

public static class TargetData {
private final String name;
private final String description;

public TargetData(String name, String description) {
this.name = name;
this.description = description;
}
}

public static abstract class TargetDataMixin {
@JsonCreator
public TargetDataMixin(@JsonProperty("name") String name, @JsonProperty("description") String description) {
}
}

所以这里TargetData上没有Jackson注释,注释取自TargetDataMixin(并且TargetDataMixin的实现完全被忽略)

关于java - 使用 Jackson 进行 JSON 反序列化 : No suitable constructor found for type - providing default constructor or annotate constructor is imposible,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30080217/

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