创建一个类型感知

创建一个类型感知

本文介绍了创建一个类型感知 Jackson 反序列化器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想配置一个 Jackson 反序列化器,它根据注释字段的目标类型执行不同的操作.

I want to configure a Jackson deserializer that act differently depending on the target type of the annotated field.

public class Car {
    @JsonSerialize(using=IdSerializer.class)
    @JsonDeserialize(using=IdDeserializer.class)
    String id
}

public class Bus {
    @JsonSerialize(using=IdSerializer.class)
    @JsonDeserialize(using=IdDeserializer.class)
    Id id
}

Jackson 序列化器知道它正在转换数据的类型,所以这是有效的:

Jackson serializers know the type from which it is converting data, so this is working:

public class IdSerializer extends JsonSerializer<Object> {
    @Override
    public void serialize(Object value, JsonGenerator jsonGen, SerializerProvider provider) throws IOException {

        // value is the annotated field class
        if(value instanceof String)
            jsonGen.writeObject(...);
        else if (value instanceof Id)
            jsonGen.writeObject(...);
        else
            throw new IllegalArgumentException();
    }
}

Jackson 反序列化器似乎不知道它将数据转换成的目标类型:

Jackson deserializers seem to do not know the target type into which it will convert data:

public class IdDeserializer extends JsonDeserializer<Object> {
    @Override
    public Object deserialize(JsonParser jp, DeserializationContext context) throws IOException {

        // what is the annotated field class?
    }
}

推荐答案

在序列化器中,您可以添加有关类型的额外信息,以便在反序列化过程中为您提供帮助.

In the serializer, you could add extra information about the type that will help you during deserialization.

从您发布的 IdSerializer 构建...

Building from your posted IdSerializer...

public class IdSerializer extends JsonSerializer<Object> {

    @Override
    public void serialize(Object value, JsonGenerator jsonGen, SerializerProvider provider) throws IOException {

        // value is the annotated field class
        if(value instanceof String){
            jsonGen.writeStartObject();
            jsonGen.writeFieldName("id");
            jsonGen.writeObject(value);
            jsonGen.writeFieldName("type");
            jsonGen.writeString("String");
            jsonGen.writeEndObject();
        }
        else if (value instanceof Id){
            Id id = (Id) value;
            jsonGen.writeStartObject();
            jsonGen.writeFieldName("id");
            jsonGen.writeString(id.getStuff());
            jsonGen.writeFieldName("type");
            jsonGen.writeString("Id");
            jsonGen.writeEndObject();
        }
        else{
            throw new IllegalArgumentException();
        }
    }
}

在你的反序列化器中,你可以解析这个类型"字段并返回一个正确的对象类型.

In your deserializer, you can parse this 'type' field and return an Object of the propertype.

这篇关于创建一个类型感知 Jackson 反序列化器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 12:05