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
with a 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
这样不行,因为下面的代码
OwnCollection<Game> gc = new Query().<Game>getParsedCollection( ... );
实际上没有通过Game
inside getParsedCollection()
. <Game>
这里只告诉编译器getParsedCollection()
应该返回OwnCollection<Game>
, but T
inside getParsedCollection()
(and parseToGenericCollection()
)仍然被擦除,因此TypeToken
无法帮助您获取其价值。
你需要通过Game.class
作为参数代替
public <T> OwnCollection<T> getParsedCollection(Class<T> elementType) { ... }
...
OwnCollection<Game> gc = new Query().getParsedCollection(Game.class);
然后使用TypeToken
链接OwnCollection
's T
with elementType
如下:
Type type = new TypeToken<OwnCollection<T>>() {}
.where(new TypeParameter<T>() {}, elementType)
.getType();
请注意,此代码使用TypeToken来自番石榴, 因为TypeToken
Gson 不支持此功能。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)