Search code examples
javapolymorphismjacksondeserialization

Polymorphism in jackson annotations: @JsonTypeInfo usage


I would like to know if @JsonTypeInfo annotation can be used for interfaces. I have set of classes which should be serialized and deserialized.

Here is what I'm trying to do. I have two implementation classes Sub1, Sub2 implementing MyInt. Some of the model classes have the interface reference for the implementation types. I would like to deserialize the objects based on polymorphism

@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=As.WRAPPER_OBJECT)
@JsonSubTypes({
    @Type(name="sub1", value=Sub1.class), 
    @Type(name="sub2", value=Sub2.class)})
public interface MyInt{
}

@JsonTypeName("sub1")
public Sub1 implements MyInt{
}

@JsonTypeName("sub2")
public Sub2 implements MyInt{
}

I get the following JsonMappingException:

Unexpected token (END_OBJECT), expected FIELD_NAME: need JSON String that contains type id


Solution

  • @JsonSubTypes.Type must have a value and a name like this,

    @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=As.WRAPPER_OBJECT, property="type")
    @JsonSubTypes({       
        @JsonSubTypes.Type(value=Dog.class, name="dog"),
        @JsonSubTypes.Type(value=Cat.class, name="cat")       
    }) 
    

    In the subclass, use @JsonTypeName("dog") to say the name.
    The values dog and cat will be set in the property named type.