简体   繁体   English

创建一个可识别类型的Jackson解串器

[英]Create a type aware Jackson deserializer

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 serializers know the type from which it is converting data, so this is working: Jackson序列化程序知道转换数据的类型,因此可以正常工作:

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 deserializers seem to do not know the target type into which it will convert data: Jackson解串器似乎不知道将数据转换成的目标类型:

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. 在序列化程序中,您可以添加有关类型的额外信息,这将在反序列化期间为您提供帮助。

Building from your posted IdSerializer... 从您发布的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 proper type. 在反序列化器中,您可以解析此“类型”字段并返回适当类型的Object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM