Dynamic polymorphic type handling with Jackson

后端 未结 4 1071
暗喜
暗喜 2020-12-31 07:40

I have a class hierarchy similar to this one:

public static class BaseConfiguration {
}

public abstract class Base {
  private BaseConfiguration configurati         


        
4条回答
  •  春和景丽
    2020-12-31 08:10

    Good answer provided by Programmer Bruce!

    I have a case of polymorphism in which I want to keep the domain objects as POJOs and not use dependencies on Jackson annotations.

    Therefore I preffer to use a custom deserializer and a Factory for decising the type or intantiating the concrete classes.

    Here is my code ... (be aware that I have an Annotation Hierarchy which are in fact "User Tags" and not Java Annotations )

    Here is the deserialization Method

    public class AnnotationDeserializer extends StdDeserializer {
    
    AnnotationDeserializer() {
        super(Annotation.class);
    }
    
    @Override
    public Annotation deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
    
        ObjectMapper mapper = (ObjectMapper) jp.getCodec();
        ObjectNode root = (ObjectNode) mapper.readTree(jp);
        Class realClass = null;
    
        Iterator> elementsIterator = root.getFields();
        while (elementsIterator.hasNext()) {
            Entry element = elementsIterator.next();
            if ("type".equals(element.getKey())) {
                realClass = AnnotationObjectFactory.getInstance()
                        .getAnnotationClass(element.getKey());
                break;
            }
        }
    
        if (realClass == null)
            return null;
        return mapper.readValue(root, realClass);
    }
    }
    

提交回复
热议问题