2014-07-01 36 views
1
public class OwnCollection<T>{ 
    private int size; 
    private List<ResponseItem<T>> data; 
} 

public class ResponseItem<T>{ 
    private String path; 
    private String key; 
    private T value; 
} 

public class Query{ 
    public <T> OwnCollection<T> getParsedCollection(...){ 
     String json = ...; //some unimportant calls where I get an valid Json to parse 
     return Result.<T>parseToGenericCollection(json); 
    } 
} 

public class Result{ 
    public static <T> OwnCollection<T> parseToGenericCollection(String result){ 
     Type type = new TypeToken<OwnCollection<T>>() {}.getType(); 
     //GsonUtil is a class where I get an Instance Gson, nothing more. 
     return GsonUtil.getInstance().fromJson(result, type); 
    } 
} 

現在我該怎麼稱呼它:解析JSON列出與通用領域的項目與GSON

OwnCollection<Game> gc = new Query().<Game>getParsedCollection(...); 

至於結果,我想,我會得到一個OwnCollection一個List<ResponseItem>其中一個響應項目包含一個字段Game。 JSON的是完全沒有問題,也沒有解析錯誤,現在唯一的問題是這樣的錯誤,當我試圖讓一個Game項目,並調用一個方法:

Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to at.da.example.Game 

回答

3

它不以這種方式工作,因爲下面的代碼

OwnCollection<Game> gc = new Query().<Game>getParsedCollection(...); 

實際上沒有通過GamegetParsedCollection()<Game>這裏只告訴編譯器getParsedCollection()應該返回OwnCollection<Game>,但T裏面的getParsedCollection()(和​​)仍然被擦除,因此TypeToken不能幫你捕獲它的值。

您需要通過Game.class作爲參數,而不是

public <T> OwnCollection<T> getParsedCollection(Class<T> elementType) { ... } 
... 
OwnCollection<Game> gc = new Query().getParsedCollection(Game.class); 

然後用TypeTokenelementType鏈接OwnCollectionT如下:

Type type = new TypeToken<OwnCollection<T>>() {} 
    .where(new TypeParameter<T>() {}, elementType) 
    .getType(); 

請注意,此代碼使用TypeToken from Guava,因爲來自Gson的TypeToken不支持此功能。

+0

沒有,但我會得到一個答案很快 - 我要去測試它。謝謝 – DominikAngerer

+0

你我的朋友真棒!完美的作品!現在讀這個的每個人 - > Upvote它! – DominikAngerer