我使用Jackson ObjectMapper将对象层次结构序列化为json String。之后我想将对象反序列化。我得到了例外如下。
重要的是 APINewDealArrangementImpl
类层次结构超出了我的更改范围 - 它是外部库的一部分。在这种情况下,我无法实现默认构造函数,也无法使用@JsonCreator
注释。
我怎样才能避免"找不到合适的构造函数"例外?是否可以使用Jackson API中的某些自定义TypeResolverBuilder
实现或其他功能来解决此问题?谢谢你的帮助。
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)
答案 0 :(得分:3)
您可以使用“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的实现)
答案 1 :(得分:0)
您需要在类中添加no args构造函数。 Jackson需要创建一个类的实例,为了做到这一点,它需要类有一个没有args的构造函数。