Jackson deserialization on multiple types

后端 未结 1 912
独厮守ぢ
独厮守ぢ 2020-12-13 10:48

I have an abstract class called Instance and then two implementations of that, UserInstance and HardwareInstance. The issue I am havin

相关标签:
1条回答
  • 2020-12-13 11:04

    Here is what I did in your same case:

    @JsonDeserialize(using = InstanceDeserializer.class)
    public abstract class Instance {
        //.. methods
    }
    
    @JsonDeserialize(as = UserInstance.class)
    public class UserInstance extends Instance {
        //.. methods
    }
    
    @JsonDeserialize(as = HardwareInstance.class)
    public class HardwareInstance extends Instance {
        //.. methods
    }
    
    public class InstanceDeserializer extends JsonDeserializer<Instance> {
        @Override
        public Instance deserialize(JsonParser jp,  DeserializationContext ctxt) throws IOException, JsonProcessingException {
            ObjectMapper mapper = (ObjectMapper) jp.getCodec();
            ObjectNode root = (ObjectNode) mapper.readTree(jp);
            Class<? extends Instance> instanceClass = null;
            if(checkConditionsForUserInstance()) {
                instanceClass = UserInstance.class;
            } else { 
                instanceClass = HardwareInstance.class;
            }   
            if (instanceClass == null){
                return null;
            }
            return mapper.readValue(root, instanceClass );
        }
    }
    

    You annotate Instance with @JsonDeserialize(using = InstanceDeserializer.class) to indicate the class to be used to deserialize the abstract class. You need then to indicate that each child class will be deserialized as themselves, otherwise they will use the parent class deserializer and you will get a StackOverflowError.

    Finally, inside the InstanceDeserializer you put the logic to deserialize into one or another child class (checkConditionsForUserInstance() for example).

    0 讨论(0)
提交回复
热议问题