简体   繁体   中英

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:

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:

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...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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