且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Jackson 中为泛型类型创建自定义反序列化器?

更新时间:2023-02-12 10:39:00

您可以实现自定义 JsonDeserializer 用于您的泛型类型,它也实现了 ContextualDeserializer.

You can implement a custom JsonDeserializer for your generic type which also implements ContextualDeserializer.

例如,假设我们有以下包含泛型值的简单包装器类型:

For example, suppose we have the following simple wrapper type that contains a generic value:

public static class Wrapper<T> {
    public T value;
}

我们现在想要反序列化如下所示的 JSON:

We now want to deserialize JSON that looks like this:

{
    "name": "Alice",
    "age": 37
}

进入一个看起来像这样的类的实例:

into an instance of a class that looks like this:

public static class Person {
    public Wrapper<String> name;
    public Wrapper<Integer> age;
}

实现ContextualDeserializer 允许我们根据字段的泛型类型参数为Person 类中的每个字段创建一个特定的反序列化器.这允许我们将名称反序列化为字符串,将年龄反序列化为整数.

Implementing ContextualDeserializer allows us to create a specific deserializer for each field in the Person class, based on the generic type parameters of the field. This allows us to deserialize the name as a string, and the age as an integer.

完整的解串器如下所示:

The complete deserializer looks like this:

public static class WrapperDeserializer extends JsonDeserializer<Wrapper<?>> implements ContextualDeserializer {
    private JavaType valueType;

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException {
        JavaType wrapperType = property.getType();
        JavaType valueType = wrapperType.containedType(0);
        WrapperDeserializer deserializer = new WrapperDeserializer();
        deserializer.valueType = valueType;
        return deserializer;
    }

    @Override
    public Wrapper<?> deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException {
        Wrapper<?> wrapper = new Wrapper<>();
        wrapper.value = ctxt.readValue(parser, valueType);
        return wrapper;
    }
}

***先在此处查看 createContextual,因为 Jackson 将首先调用它.我们从 BeanProperty 中读取字段的类型(例如 Wrapper),然后提取第一个泛型类型参数(例如 String).然后我们创建一个新的解串器并将内部类型存储为 valueType.

It is best to look at createContextual here first, as this will be called first by Jackson. We read the type of the field out of the BeanProperty (e.g. Wrapper<String>) and then extract the first generic type parameter (e.g. String). We then create a new deserializer and store the inner type as the valueType.

一旦在这个新创建的反序列化器上调用 deserialize,我们可以简单地要求 Jackson 将值反序列化为内部类型而不是整个包装类型,并返回一个新的 Wrapper 包含反序列化的值.

Once deserialize is called on this newly created deserializer, we can simply ask Jackson to deserialize the value as the inner type rather than as the whole wrapper type, and return a new Wrapper containing the deserialized value.

为了注册这个自定义反序列化器,我们需要创建一个包含它的模块,并注册该模块:

In order to register this custom deserializer, we then need to create a module that contains it, and register that module:

SimpleModule module = new SimpleModule()
        .addDeserializer(Wrapper.class, new WrapperDeserializer());

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(module);

如果我们然后尝试反序列化上面的示例 JSON,我们可以看到它按预期工作:

If we then try to deserialize the example JSON from above, we can see that it works as expected:

Person person = objectMapper.readValue(json, Person.class);
System.out.println(person.name.value);  // prints Alice
System.out.println(person.age.value);   // prints 37

Jackson 文档中有更多关于上下文解串器如何工作的详细信息.

There are some more details about how contextual deserializers work in the Jackson documentation.