How to create a custom deserializer in Jackson for a generic type?

前端 未结 3 1195
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 05:08

Imagine the following scenario:

class  Foo {
    ....
}

class Bar {
    Foo foo;
}

I want to write a cu

3条回答
  •  臣服心动
    2020-11-29 05:18

    This is how you can access/resolve {targetClass} for a Custom Jackson Deserializer. Of course you need to implement ContextualDeserializer interface for this.

    public class WPCustomEntityDeserializer extends JsonDeserializer 
                  implements ContextualDeserializer {
    
        private Class targetClass;
    
        @Override
        public Object deserialize(JsonParser jp, DeserializationContext ctxt)
                throws IOException, JsonProcessingException {
    
            ObjectCodec oc = jp.getCodec();
            JsonNode node = oc.readTree(jp);
    
            //Your code here to customize deserialization
            // You can access {target class} as targetClass (defined class field here)
            //This should build some {deserializedClasObject}
    
            return deserializedClasObject;
    
        }   
    
        @Override
        public JsonDeserializer createContextual(DeserializationContext ctxt, BeanProperty property){
            //Find here the targetClass to be deserialized  
            String targetClassName=ctxt.getContextualType().toCanonical();
            try {
                targetClass = Class.forName(targetClassName);
            } catch (ClassNotFoundException e) {            
                e.printStackTrace();
            }
            return this;
        }
    }
    
        

    提交回复
    热议问题