Java 类型泛型作为 GSON 的参数 [英] Java Type Generic as Argument for GSON
问题描述
在 GSON 中获取您执行的对象列表
In GSON to get a list of objects you do
Gson gson = new Gson();
Type token = new TypeToken<List<MyType>>(){}.getType();
return gson.fromJson(json, token);
效果很好,但我想更进一步,对 MyType 进行参数化,这样我就可以有一个通用函数来使用此代码解析对象列表
It works great, but I want to go further and have MyType parametrized so I can have a common function to parse list of objects with this code
// the common function
public <T> List<T> fromJSonList(String json, Class<T> type) {
Gson gson = new Gson();
Type collectionType = new TypeToken<List<T>>(){}.getType();
return gson.fromJson(json, collectionType);
}
// the call
List<MyType> myTypes = parser.fromJSonList(jsonString, MyType.class);
遗憾的是返回一个 StringMap 数组,而不是类型.T 被解释为另一种泛型类型,而不是我的类型.有什么解决方法吗?
Sadly returns an array of StringMaps, not the type. T is being interpreted as another generic type, not my type. Any workaround ?
推荐答案
从 gson 2.8.0
开始,您可以使用 TypeToken#getParametized((Type rawType, Type... typeArguments))
来创建 typeToken
,然后 getType()
应该可以做到这一点.
Since gson 2.8.0
, you can use TypeToken#getParametized((Type rawType, Type... typeArguments))
to create the typeToken
, then getType()
should do the trick.
例如:
TypeToken.getParameterized(List.class, myType).getType();
这篇关于Java 类型泛型作为 GSON 的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!