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

前端 未结 3 1197
佛祖请我去吃肉
佛祖请我去吃肉 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:26

    If the target itself is a generic type then property will be null, for that you'll need to get the valueTtype from the DeserializationContext:

    @Override
    public JsonDeserializer createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException {
        if (property == null) { //  context is generic
            JMapToListParser parser = new JMapToListParser();
            parser.valueType = ctxt.getContextualType().containedType(0);
            return parser;
        } else {  //  property is generic
            JavaType wrapperType = property.getType();
            JavaType valueType = wrapperType.containedType(0);
            JMapToListParser parser = new JMapToListParser();
            parser.valueType = valueType;
            return parser;
        }
    }
    

提交回复
热议问题