Jackson deserialize based on type

后端 未结 4 1616
夕颜
夕颜 2020-12-15 22:09

Lets say I have JSON of the following format:

{
    \"type\" : \"Foo\"
    \"data\" : {
        \"object\" : {
            \"id\" : \"1\"
            \"fizz\         


        
4条回答
  •  無奈伤痛
    2020-12-15 23:09

    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);  
    

提交回复
热议问题