使用Gson将Json解析为带有通用字段的项目列表
public class OwnCollection{ private int size; private List<ResponseItem> data; } public class ResponseItem{ private String path; private String key; private T value; } public class Query{ public OwnCollection getParsedCollection( ... ){ String json = ...; //some unimportant calls where I get an valid Json to parse return Result.parseToGenericCollection(json); } } public class Result{ public static OwnCollection parseToGenericCollection(String result){ Type type = new TypeToken<OwnCollection>() {}.getType(); //GsonUtil is a class where I get an Instance Gson, nothing more. return GsonUtil.getInstance().fromJson(result, type); } }
现在我怎么称呼它:
OwnCollection gc = new Query().getParsedCollection( ... );
结果我想,我将获得一个带有List
的OwnCollection
,其中一个响应项包含类Game
的字段。 Json非常好,并且没有解析错误,当我尝试获取一个Game
项并调用方法时,现在唯一的问题就是这个错误:
Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to at.da.example.Game
它不能以这种方式工作,因为下面的代码
OwnCollection gc = new Query(). getParsedCollection( ... );
实际上并没有在getParsedCollection()
传递Game
。
这里只告诉编译器getParsedCollection()
应该返回OwnCollection
,但是getParsedCollection()
(和parseToGenericCollection()
)中的T仍然被擦除,因此TypeToken
无法帮助你捕获它的值。
您需要将Game.class
作为参数传递
public OwnCollection getParsedCollection(Class elementType) { ... } ... OwnCollection gc = new Query().getParsedCollection(Game.class);
然后使用TypeToken
将OwnCollection
的T
与elementType
链接,如下所示:
Type type = new TypeToken>() {} .where(new TypeParameter() {}, elementType) .getType();
请注意,此代码使用Guava中的TypeToken
,因为Gson中的TypeToken
不支持此function。