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
. 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:
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()
. <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.
You need to pass Game.class
as a parameter instead
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:
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.
来源:https://stackoverflow.com/questions/24505314/parsing-json-to-list-of-items-with-generic-field-with-gson