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);
}
}
现在我怎么称呼它:
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
答案 0 :(得分:3)
它不会以这种方式工作,因为以下代码
OwnCollection<Game> gc = new Query().<Game>getParsedCollection( ... );
实际上并没有在Game
内通过getParsedCollection()
。 <Game>
这里只告诉编译器getParsedCollection()
应该返回OwnCollection<Game>
,但T
{和getParsedCollection()
内的parseToGenericCollection()
仍然被删除,因此TypeToken
无法帮助您捕捉其价值。
您需要将Game.class
作为参数传递
public <T> OwnCollection<T> getParsedCollection(Class<T> elementType) { ... }
...
OwnCollection<Game> gc = new Query().getParsedCollection(Game.class);
然后使用TypeToken
将OwnCollection
&#39; T
与elementType
关联起来,如下所示:
Type type = new TypeToken<OwnCollection<T>>() {}
.where(new TypeParameter<T>() {}, elementType)
.getType();
请注意,此代码使用TypeToken
from Guava,因为Gson的TypeToken
不支持此功能。