Parsing Json to List of Items with generic field with Gson

偶尔善良 提交于 2019-12-01 13:25:23

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!