【问题标题】:Deserialize external library classes with a builder method as a constructor [duplicate]使用构建器方法作为构造函数反序列化外部库类[重复]
【发布时间】:2017-11-26 12:52:10
【问题描述】:

我有这样的课:

class MyClass {
    CustomList<String> list = ListUtils.createCustomList();
}

interface CustomList implements java.util.List 在哪里,所以它不能用构造函数反序列化。相反,有一个 class ListUtils 创建一个实现实例。接口和实用程序类都在外部库中,因此我无法对其进行注释。

我如何告诉 Jackson 在遇到 CustomList 时应该调用 ListUtils.createCustomList() 而不是构造函数?是否有 mixin 配置,我可以指定从类型到构造方法的映射,或者我需要编写的自定义反序列化器?

【问题讨论】:

    标签: java jackson json-deserialization


    【解决方案1】:

    这里有两个问题,第一个是如何告诉Jackson 使用另一个类ListUtils 的静态方法来创建CustomList 类的实例。 @JsonCreator 可以用于CustomList 的静态方法或通过混合使用。不幸的是,您不能在ListUtils 上使用它。为此有一个open issue

    在实现/发布上述请求之前,您必须创建一个自定义反序列化器。这种反序列化器的骨架实现如下所示:

    class ListDeserializer extends JsonDeserializer<CustomList> {
        @Override
        public CustomList deserialize(JsonParser p, DeserializationContext c) throws IOException {
            return ListUtils.createCustomList();
        }
    }
    

    使用其他初始化步骤扩展此方法,例如使用JsonParser 解析元素,并在返回之前将它们添加到列表中。查看示例here。您可以在 ObjectMapper 上指定要使用的此反序列化程序,而无需任何注释:

    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addDeserializer(CustomList.class, new ListDeserializer());
    mapper.registerModule(module);
    

    【讨论】:

    • 谢谢。关于在构建后填充列表,我不能告诉杰克逊照原样填充列表吗?我只想更改初始化步骤,然后照常继续。
    • 找到了我正在寻找的答案并标记为重复,但无论如何这个答案都是正确的。
    猜你喜欢
    • 2020-01-11
    • 1970-01-01
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 2015-02-21
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多