我有以下用例:我的ObjRef子类的吨数是这种形式(代码简化):
public class PlatformRef extends ObjRef {
public PlatformRef() {}
public PlatformRef(long id) {}
public PlatformRef(Long id) {);
}
反序列化时(我在要反序列化的对象中有这些类的数组,我的映射器使用默认类型)
...
"platforms" : [ {
"id" : 20001,
"name" : "my_platformRef_name",
"idAsLong" : 20001
}, {
"id" : 30001,
"name" : null,
"idAsLong" : 30001
} ]
...
jackson 2.4.3 throws:com.fasterxml.jackson.databind.JsonMappingException:冲突的长创作者
我尝试使用ValueInstantiators#findValueInstantiator指向这些ObjRef子类的自定义实例化器。
它失败了,因为BasicDeserializerFactory#findValueInstantiator首先找到bean的所有可能的ctors(如上所述失败),然后才尝试找到用户定义的那些。
我怎样才能解决这个问题,因为:
答案 0 :(得分:0)
使用自定义的AnnotationIntrospector对其进行排序:
mapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector() {
@Override
public Object findValueInstantiator(AnnotatedClass ac) {
if (ObjRef.class.isAssignableFrom(ac.getAnnotated())) {
return new StdCtorValueInstantiator(ac);
}
return super.findValueInstantiator(ac);
}
});
private static class StdCtorValueInstantiator extends ValueInstantiator {
private AnnotatedClass annotated;
public StdCtorValueInstantiator(AnnotatedClass ac) {
annotated = ac;
}
@Override
public String getValueTypeDesc() {
return "Subclass_of_ObjRef";
}
@Override
public boolean canCreateUsingDefault() {
return true;
}
@Override
public Object createUsingDefault(DeserializationContext ctxt) throws IOException {
try {
return annotated.getDefaultConstructor().getAnnotated().newInstance();
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new IOException("Could not create an instance of " + annotated.getAnnotated()
+ " using the default c-tor");
}
}
}