Gson:解析泛型集合 [英] Gson: parse generic collections
问题描述
是否有可能创建一个方法,从jsson解析泛型集合?上面的问题不起作用,因为在运行时,gson在这里返回LinkedHasmaps的ArrayList,但是在编译时没有错误。
Is it possible to create a method, that parses a generic collection from jsson? My aproach above doesn't work, because at runtime gson returns an ArrayList of LinkedHasmaps here, however there is no errors at compile time.
private <T> ArrayList<T> readArray(String json)
{
Gson gson = new Gson();
Type collType = new TypeToken<ArrayList<T>>() {
}.getType();
return gson.fromJson(json, collType);
}
我已经在这里看过一些类似的问题:使用Gson的泛型类型,但我没有找到解决方案,这真的起作用。
I have already looked at some similar questions here like: Using a generic type with Gson, but I found no solution, that really works.
推荐答案
TypeToken需要你在编译时修改类型参数。像 ArrayList< String>
或其他。 ArrayList< T>
不起作用。
The TypeToken stuff requires you to have the type parameters fixed at compile time. Like ArrayList<String>
or something. ArrayList<T>
will not work.
如果您可以获取运行时以某种方式传递的T的类对象,那么你可以尝试我在中建议的解决方案。我如何在运行时从泛型类型定义和运行时类型参数中构建一个Java类型对象?
If you can get the class object for T passed in somehow at runtime, then you can try the solution I suggested in How do I build a Java type object at runtime from a generic type definition and runtime type parameters?
这篇关于Gson:解析泛型集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!