杰克逊第三方类,没有默认构造函数

2022-09-01 09:02:01

我正在尝试使用 Jackson 来读取/写入我的 POJO 到 Json/从 Json 写入。截至目前,我已经配置了它并为我的类工作,除了第三方类。尝试在Json中读取时,我收到错误:

org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type

经过几次快速的Google搜索后,我的类似乎需要默认构造函数用注释覆盖默认构造函数。不幸的是,失败的类来自第三方库,并且该类没有默认构造函数,我显然不能覆盖代码。

所以我的问题是,我对此能做些什么,还是我只是运气不好?

谢谢。


答案 1

你可以利用Jackson的Mix-Ins功能,再加上Creator功能。Mix-Ins 功能减轻了对原始第三方代码进行批注的需要,而 Creator 功能则提供了用于创建自定义实例的机制。

对于更多的自定义,编写自定义反序列化程序并不太复杂。


答案 2

一种方法是实现自定义 JsonDeserializer 来创建实例,并使用@JsonDeserialize注释该类型的字段。与例如 mixins 相比,这种方法的一个优点是它不需要修改 .ObjectMapper

允许从表示值的 a 映射到所需类型。JsonNode

缺少构造函数的类型

public class ThirdPartyType {
    private String stringProperty;

    private int intProperty;

    private Object[] arrayProperty;

    public ThirdPartyType(String a, int b, Object[] c) {
        this.stringProperty = a;
        this.intProperty = b;
        this.arrayProperty = c;
    }
    
    // Getters and setters go here
}

自定义反序列化程序

import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdNodeBasedDeserializer;

import java.io.IOException;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.StreamSupport;

public class ThirdPartyTypeDeserializer 
        extends StdNodeBasedDeserializer<ThirdPartyType> {
    protected ThirdPartyTypeDeserializer() {
        super(ThirdPartyType.class);
    }

    @Override
    public ThirdPartyType convert(JsonNode root, DeserializationContext ctxt)
            throws IOException {
        return new ThirdPartyType(
                root.get("stringProperty").asText(null),
                root.get("intProperty").asInt(),
                StreamSupport.stream(
                        Spliterators.spliteratorUnknownSize(
                                root.get("arrayProperty").elements(),
                                Spliterator.ORDERED),
                        false).toArray());
    }
}

包含第三方类型的类型

public class EnclosingClass {
    @JsonDeserialize(using = ThirdPartyTypeDeserializer.class)
    private ThirdPartyType thirdPartyProperty;
    
    // Getters and setters go here
}

检索值

String json = "{\"thirdPartyProperty\": {"
        + "\"stringProperty\": \"A\", "
        + "\"intProperty\": 5, "
        + "\"arrayProperty\": [1, \"B\", false]"
        + "}}";
ObjectMapper objectMapper = new ObjectMapper();
EnclosingClass enclosingClass =
        objectMapper.readValue(json, EnclosingClass.class);