Gson 2.2.2無法序列化Object1中的字段。GSON 2.2.2無法序列化類型「?extend someInterface」
public class Test {
public static void main(String[] args){
Object1 o1 = new Object1();
List<Interface1> list1 = new ArrayList<Interface1>();
Interface1 f1 = new InterfaceImp();
list1.add(f1);
o1.field = list1;
System.out.println(new Gson().toJson(o1));
}
}
interface Interface1{}
class InterfaceImp implements Interface1{
public String s = "123";
}
class Object1 {
public List<? extends Interface1> field ;
}
調試運行時,我找到了方法TypeAdapterRuntimeTypeWrapper:
private Type getRuntimeTypeIfMoreSpecific(Type type, Object value) {
if (value != null && (type == Object.class || type instanceof TypeVariable<?> || type instanceof Class<?>)) {
type = value.getClass();
}
return type;
}
不返回value.getClass()。參數'type'(?擴展Interface1)使得if測試可以快速進行。一個錯誤?
嗯,*你期望它會返回什麼樣的類型?你正在使用有界的通配符,這意味着你沒有類型。你......不能那樣做。 –