JSON 使用 Jackson 反序列化:找不到适合类型的构造函数 - 提供默认构造函数或注释构造函数是不可能的

JSON deserialisation using Jackson: No suitable constructor found for type - providing default constructor or annotate constructor is imposible

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

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

如何避免 "No suitable constructor found" 异常?是否可以使用 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)

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

@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的实现)