Jackson deserialize based on type

Annotations-only approach

Alternatively to the custom deserializer approach, you can have the following for an annotations-only solution (similar to the one described in Spunc’s answer, but using type as an external property):

public abstract class AbstractData {

    private Owner owner;

    private Metadata metadata;

    // Getters and setters
public static final class FooData extends AbstractData {

    private Foo object;

    // Getters and setters
public static final class BarData extends AbstractData {

    private Bar object;

    // Getters and setters
public class Wrapper {

    private String type;

    @JsonTypeInfo(use = Id.NAME, property = "type", include = As.EXTERNAL_PROPERTY)
    @JsonSubTypes(value = { 
            @JsonSubTypes.Type(value = FooData.class, name = "Foo"),
            @JsonSubTypes.Type(value = BarData.class, name = "Bar") 
    private AbstractData data;

    // Getters and setters

In this approach, @JsonTypeInfo is set to use type as an external property to determine the right class to map the data property.

The JSON document can be deserialized as following:

ObjectMapper mapper = new ObjectMapper();
Wrapper wrapper = mapper.readValue(json, Wrapper.class);  

Leave a Comment