2014-07-01 37 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