使用构建器方法作为构造函数反序列化外部库 类

Deserialize external library classes with a builder method as a constructor

我有一个 class 这样的:

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

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

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

这里有 2 个问题,第一个是如何告诉 Jackson 使用另一个 class ListUtils 的静态方法来创建 CustomList [=27 的实例=].您可以在 CustomList 的静态方法上或通过混合使用 @JsonCreator。不幸的是,您不能在 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);