2014-01-22 32 views
0

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測試可以快速進行。一個錯誤?

+0

嗯,*你期望它會返回什麼樣的類型?你正在使用有界的通配符,這意味着你沒有類型。你......不能那樣做。 –

回答

0

我認爲你需要指定你使用的列表

檢查此鏈接

https://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Examples

例如泛型類型,序列化的列表:

Type type = new TypeToken<List<Interface1>>(){}.getType(); 
String s = new Gson().toJson(list1, type); 

工作代碼(測試)

public static void main(String[] args) { 
    Object1 o1 = new Object1(); 
    List<Interface1> list1 = new ArrayList<Interface1>(); 
    Interface1 f1 = new InterfaceImp(); 
    list1.add(f1); 
    list1.add(f1); 
    o1.field = list1; 

    String s = getGsonWithAdapters().toJson(o1); 
    System.out.println(s); 
} 

public static Gson getGsonWithAdapters() { 
    GsonBuilder gb = new GsonBuilder(); 
    gb.serializeNulls(); 
    gb.registerTypeAdapter(Object1.class, new CustomAdapter()); 
    return gb.create(); 
} 

public static class CustomAdapter implements JsonSerializer<Object1> { 
    @Override 
    public JsonElement serialize(Object1 obj, Type type, 
      JsonSerializationContext jsc) { 
     JsonObject jsonObject = new JsonObject(); 
     Type t = new TypeToken<List<Interface1>>() {}.getType(); 
     jsonObject.add("field", new Gson().toJsonTree(obj.field, t)); 
     return jsonObject; 
    } 
} 
+0

我已經通過使用自定義適配器解決了這個問題,但爲什麼不在這種情況下讓'getRuntimeTypeIfMoreSpecific'方法返回實型? –

+0

其實我不知道,我有一個類似的問題,我也解決了自定義適配器,它始終工作,但它需要手動添加一些代碼行......無論如何希望我的回答幫助;) – Alessio

+0

謝謝你的回答:) –