我在Jackson中序列化通用对象时遇到了问题。我找到了一个解决方法,但我仍然不知道为什么我的原始解决方案不起作用。这是我的设置:
public class ClassA<P>{
protected final LinkedList<P> list;
public ClassA(LinkedList<P> list){
this.list = list;
}
}
@JsonValue
public class ClassB extends ClassA<ParamClass>{
public ClassB(LinkedList<ParamClass> list) {
super(list);
}
@JsonCreator
public ClassB(int[] array) {
this(getList(array));
}
public int[] serialize(){
...
}
}
public class ParamClass extends BaseParamClass{
public int getInt(){
...
}
}
以下是我目前使用的序列化方法的代码:
@JsonValue
public int[] serialize(){
int[] array = new int[list.size()];
for (int i = 0; i < array.length; i++) {
BaseParamClass paramClass = list.get(i);
locationsArray[i] = paramClass.getInt();
}
return locationsArray;
}
这是应该起作用的,但不是:
@JsonValue
public int[] serialize(){
int[] array = new int[list.size()];
for (int i = 0; i < array.length; i++) {
ParamClass paramClass = list.get(i);
locationsArray[i] = paramClass.getInt();
}
return locationsArray;
}
对于第二种情况,我得到了这个例外:
com.fasterxml.jackson.databind.JsonMappingException(packages.BaseParamClass cannot be cast to another.packages.ParamClass)
这是什么原因?从ClassB中的类型规范来看,很明显只能在列表中使用ParamClass而不是BaseParamClass。我想念一下吗?
答案 0 :(得分:0)
你需要告诉杰克逊ObjectMapper
目标类的通用类型:
ObjectMapper mapper = new ObjectMapper();
TypeFactory factory = mapper.getTypeFactory();
JavaType paramClassType = factory.constructType(ParamClass.class);
JavaType classBType = factory.constructSimpleType(ClassB.class, new JavaType[]{paramClassType});
mapper.readValue(src, classBType);