How do I get the type to convert to when deserializing from Jackson

55 views Asked by At

It's trivial to generically serialize any type (e.g. a Joda DateTime) by delegating to Joda Convert like this:

public class ToJodaConverter extends SerializerBase<Object> {
    protected ToJodaConverter() {
        super(Object.class);
    }

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeString(StringConvert.INSTANCE.convertToString(value));
    }
}

I'd like to deserialize in the same way, something like this:

public class FromJodaConverter extends StdDeserializer<Object> {
    protected FromJodaConverter() {
        super(Object.class);
    }

    @Override
    public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
        return StringConvert.INSTANCE.convertFromString(TYPE, jp.getText());
    }
}

But how do I get the TYPE that should be converted to? I've been searching for other subclasses of JsonDeserializer, but couldn't find out how to do this, or how to just implement the other deserialize method with the type parameter.

1

There are 1 answers

1
JB Nizet On

You need to specify the type you want to deserialize to:

public class FromJodaConverter<T> extends StdDeserializer<T> {
    public FromJodaConverter(Class<T> clazz) {
        super(clazz);
    }

    @Override
    public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
        return StringConvert.INSTANCE.convertFromString(handledType(), jp.getText());
    }
}

So, to create a FromJodaConverter that deserializes instances of Foo, you would use

new FromJodaConverter(Foo.class);

And to create a FromJodaConverter that deserializes instances of Baz, you would use

new FromJodaConverter(Baz.class);