具有动态 ArrayList 项类型的 Gson TypeToken [英] Gson TypeToken with dynamic ArrayList item type

查看:34
本文介绍了具有动态 ArrayList 项类型的 Gson TypeToken的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

Type typeOfObjectsList = new TypeToken<ArrayList<myClass>>() {}.getType();
List<myClass> objectsList = new Gson().fromJson(json, typeOfObjectsList);

它将 JSON 字符串转换为对象的 List.但现在我想要这个 ArrayList 在运行时定义的动态类型(不仅仅是 myClass).

It converts a JSON string to a List of objects. But now I want to have this ArrayList with a dynamic type (not just myClass), defined at runtime.

ArrayList 的项目类型将使用 reflection 定义.

The ArrayList's item type will be defined with reflection.

我试过了:

    private <T> Type setModelAndGetCorrespondingList2(Class<T> type) {
        Type typeOfObjectsListNew = new TypeToken<ArrayList<T>>() {}.getType();
        return typeOfObjectsListNew;
    }

但它不起作用.这是个例外:

But it doesn't work. This is the exception:

java.sql.SQLException: Fail to convert to internal representation: {....my json....}

推荐答案

您提议的语法无效.以下

The syntax you are proposing is invalid. The following

new TypeToken<ArrayList<Class.forName(MyClass)>>

无效,因为您试图在需要类型名称的地方传递方法调用.

is invalid because you're trying to pass a method invocation where a type name is expected.

以下

new TypeToken<ArrayList<T>>() 

是不可能的,因为泛型(类型擦除)和反射是如何工作的.整个 TypeToken hack 有效,因为 Class#getGenericSuperclass() 执行以下操作

is not possible because of how generics (type erasure) and reflection works. The whole TypeToken hack works because Class#getGenericSuperclass() does the following

返回代表实体直接超类的类型(类、接口、原始类型或void)由此类表示.

Returns the Type representing the direct superclass of the entity (class, interface, primitive type or void) represented by this Class.

如果超类是参数化类型,返回的Type对象必须准确反映源中使用的实际类型参数代码.

If the superclass is a parameterized type, the Type object returned must accurately reflect the actual type parameters used in the source code.

换句话说,如果它看到 ArrayList,那就是 ParameterizedType 它将返回,你将无法提取类型变量 T 本来会有.

In other words, if it sees ArrayList<T>, that's the ParameterizedType it will return and you won't be able to extract the compile time value that the type variable T would have had.

TypeParameterizedType 都是接口.您可以提供自己实现的实例.

Type and ParameterizedType are both interfaces. You can provide an instance of your own implementation.

这篇关于具有动态 ArrayList 项类型的 Gson TypeToken的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆