Get the detected generic type inside Jackson's JsonDeserializer
Got an answer on the Jackson Google group directly from the author.
The key thing to understand is that JsonDeserializer
s are created/contextualized once, and they receive the full type and other information at that moment only. To get a hold of this info, the deserializer needs to implement ContextualDeserializer
. Its createContextual
method is called to initialize a deserializer instance, and has access to the BeanProperty
which also gives the full JavaType
.
So it could look something like this in the end:
public class MapDeserializer extends JsonDeserializer implements ContextualDeserializer { private JavaType type; public MapDeserializer() { } public MapDeserializer(JavaType type) { this.type = type; } @Override public JsonDeserializer<?> createContextual(DeserializationContext deserializationContext, BeanProperty beanProperty) throws JsonMappingException { //beanProperty is null when the type to deserialize is the top-level type or a generic type, not a type of a bean property JavaType type = deserializationContext.getContextualType() != null ? deserializationContext.getContextualType() : beanProperty.getMember().getType(); return new MapDeserializer(type); } @Override public Map deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { //use this.type as needed } ...}
Registered and used as normal:
ObjectMapper mapper = new ObjectMapper();SimpleModule module = new SimpleModule();module.addDeserializer(Map.class, new MapDeserializer());mapper.registerModule(module);