[英]Parsing Json to List of Items with generic field with Gson
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);
}
}
Now how I call it: 现在我怎么称呼它:
OwnCollection<Game> gc = new Query().<Game>getParsedCollection( ... );
As result I thought, I will get a OwnCollection
with a List<ResponseItem>
where one Response Item contains a field of the class Game
. 结果我想,我将获得一个带有
List<ResponseItem>
的OwnCollection
,其中一个响应项包含类Game
的字段。 The Json is perfectly fine and there is no parsing error the only problem now is this error when I try to get one Game
item and call a method: Json非常好,并且没有解析错误,当我尝试获取一个
Game
项并调用方法时,现在唯一的问题就是这个错误:
Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to at.da.example.Game
It doesn't work this way, because the following code 它不能以这种方式工作,因为下面的代码
OwnCollection<Game> gc = new Query().<Game>getParsedCollection( ... );
actually doesn't pass Game
inside getParsedCollection()
. 实际上并没有在
getParsedCollection()
传递Game
。 <Game>
here only tells the compiler that getParsedCollection()
is supposed to return OwnCollection<Game>
, but T
inside getParsedCollection()
(and parseToGenericCollection()
) remains erased, therefore TypeToken
cannot help you to capture its value. <Game>
这里只是告诉编译器getParsedCollection()
应该返回OwnCollection<Game>
,但T
内getParsedCollection()
和parseToGenericCollection()
保持消除,因此TypeToken
不能帮你捕捉到它的价值。
You need to pass Game.class
as a parameter instead 您需要将
Game.class
作为参数传递
public <T> OwnCollection<T> getParsedCollection(Class<T> elementType) { ... }
...
OwnCollection<Game> gc = new Query().getParsedCollection(Game.class);
and then use TypeToken
to link OwnCollection
's T
with elementType
as follows: 然后使用
TypeToken
将OwnCollection
的T
与elementType
链接,如下所示:
Type type = new TypeToken<OwnCollection<T>>() {}
.where(new TypeParameter<T>() {}, elementType)
.getType();
Note that this code uses TypeToken
from Guava , because TypeToken
from Gson doesn't support this functionality. 请注意,此代码使用Guava中的
TypeToken
,因为Gson中的TypeToken
不支持此功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.