经过一些测试,我发现@jax的答案有问题.
正如@Staxman指出的那样,在构造反序列化器时会调用createContextual(),而不是在每个反序列化过程中调用.并且createContextual返回的反序列化器将由Jackson库缓存.因此,如果您的反序列化器使用多于一种类型(例如公共父类的子类型),它将抛出类型不匹配异常,因为targetClass属性将是Jackson库缓存的最后一种类型.
正确的解决方案应该是:
public class JsonApiDeserializer extends JsonDeserializer implements
ContextualDeserializer {
private Class> targetClass;
public JsonApiDeserializer() {
}
public JsonApiDeserializer(Class> targetClass) {
this.targetClass = targetClass;
}
@Override
public Object deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
Object clazz = targetClass.newInstance();
//Now I have an instance of the annotated class I can populate the fields via reflection
return clazz;
}
@Override
public JsonDeserializer> createContextual(DeserializationContext ctxt,
BeanProperty property) throws JsonMappingException {
//gets the class type of the annotated class
targetClass = ctxt.getContextualType().getRawClass();
//this new JsonApiDeserializer will be cached
return new JsonApiDeserializer(targetClass);
}
}