Gson TypeToken With Dynamic List Item Type – 具有动态列表项类型的 Gson TypeToken

最后修改: 2024年 3月 4日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll discuss converting a JSON array into an equivalent java.util.List object. Gson is a Java library by Google that helps convert JSON strings to Java objects and vice versa.

在本教程中,我们将讨论如何将 JSON 数组转换为等价的 java.util.List 对象。Gson 是 Google 开发的 Java 库,可帮助将 JSON 字符串转换为 Java 对象,反之亦然。

The Gson class in this library has the method fromJson() that takes in two arguments, the first argument is JSON String and the second argument is of type java.lang.reflect.Type. The method converts the JSON String to an equivalent Java object of type represented by its second argument.

该库中的 Gson 类有一个接收两个参数的方法 fromJson(),第一个参数是 JSON String,第二个参数是 java.lang.reflect.Type 类型。该方法将 JSON String 转换为第二个参数所代表类型的等价 Java 对象。

We’ll come up with a generic method, say convertJsonArrayToListOfAnyType(String jsonArray, T elementType), that can convert the JSON array into List<T>, where T is the type of elements in the List.

我们将创建一个通用方法,例如 convertJsonArrayToListOfAnyType(String jsonArray, T elementType), 它可以将 JSON 数组转换为 列表<T>,其中 T 是 List 中元素的类型。

Let’s understand more about this.

让我们进一步了解一下。

2. Problem Description

2.问题描述

Let’s assume we have two JSON arrays, one for Student and one for School:

假设我们有两个 JSON 数组,一个是 Student 数组,另一个是 School 数组:

final String jsonArrayOfStudents =
    "["
      + "{\"name\":\"John\", \"grade\":\"1\"}, "
      + "{\"name\":\"Tom\", \"grade\":\"2\"}, "
      + "{\"name\":\"Ram\", \"grade\":\"3\"}, "
      + "{\"name\":\"Sara\", \"grade\":\"1\"}"
  + "]";
final String jsonArrayOfSchools =
    "["
      + "{\"name\":\"St. John\", \"city\":\"Chicago City\"}, "
      + "{\"name\":\"St. Tom\", \"city\":\"New York City\"}, "
      + "{\"name\":\"St. Ram\", \"city\":\"Mumbai\"}, "
      + "{\"name\":\"St. Sara\", \"city\":\"Budapest\"}"
  + "]";

Normally, we can use the Gson class to convert the arrays into List objects:

通常,我们可以使用 Gson 类将数组转换为 List 对象:

@Test
void givenJsonArray_whenListElementTypeDynamic_thenConvertToJavaListUsingTypeToken() {
    Gson gson = new Gson();
    TypeToken<List<Student>> typeTokenForListOfStudents = new TypeToken<List<Student>>(){};
    TypeToken<List<School>> typeTokenForListOfSchools = new TypeToken<List<School>>(){};
    List<Student> studentsLst = gson.fromJson(jsonArrayOfStudents, typeTokenForListOfStudents.getType());
    List<School> schoolLst = gson.fromJson(jsonArrayOfSchools, typeTokenForListOfSchools.getType());
    assertAll(
      () -> studentsLst.forEach(e -> assertTrue(e instanceof Student)),
      () -> schoolLst.forEach(e -> assertTrue(e instanceof School))
    );
}

We created the TypeToken objects for List<Student> and List<School>. Finally, using the TypeToken objects, we got the Type objects and then converted the JSON arrays into List<Student> and List<School>.

我们为 List<Student>List<School> 创建了 TypeToken 对象。最后,我们使用 TypeToken 对象获得了 Type 对象,然后将 JSON 数组转换为List<Student>List<School>

To promote reuse, let’s try creating a generic class with a method that can take the element type in the List and return the Type object:

为了促进重复使用,让我们尝试创建一个泛型类,该类中的方法可以接收 List 中的元素类型,并返回 Type 对象:

class ListWithDynamicTypeElement<T> {
    Type getType() {
        TypeToken<List<T>> typeToken = new TypeToken<List<T>>(){};
        return typeToken.getType();
    }
}

We’re instantiating a generic TypeToken<List<T>> for a given element type T. Then we’re returning the corresponding Type object. The list element type is available only at runtime.

我们正在为给定的元素类型 T 实例化一个通用的 TypeToken<List<T>> 。然后,我们将返回相应的 Type 对象。列表元素类型仅在运行时可用。

Let’s see the method in action:

让我们看看该方法的实际效果:

@Test
void givenJsonArray_whenListElementTypeDynamic_thenConvertToJavaListUsingTypeTokenFails() {
    Gson gson = new Gson();
    List<Student> studentsLst = gson.fromJson(jsonArrayOfStudents, new ListWithDynamicTypeElement<Student>().getType());
    assertFalse(studentsLst.get(0) instanceof Student);
    assertThrows(ClassCastException.class, () -> studentsLst.forEach(e -> assertTrue(e instanceof Student)));
}

While the method compiles, it fails in runtime and raises a ClassCastException when we try to iterate over studentLst. Also, we see that the elements in the list are not of type Student.

虽然该方法可以编译,但在运行时却失败了,当我们尝试遍历 studentLst 时,会引发 ClassCastException 异常。此外,我们还发现列表中的元素不属于 Student 类型。

3. Solution Using getParameterized() in TypeToken

3.在 TypeToken 中使用 getParameterized() 的解决方案

In the Gson 2.10 version, the getParamterized() method was introduced in the class TypeToken. This enabled developers to handle scenarios where the type information of the list elements is not available during the compile time.

在 Gson 2.10 版本中,getParamterized()方法被引入到类TypeToken中。这使开发人员能够处理在编译期间无法获得列表元素类型信息的情况。

Let’s see how this new method helps return the Type information of parameterized classes:

让我们看看这个新方法如何帮助返回参数化类的 Type 信息:

Type getGenericTypeForListFromTypeTokenUsingGetParameterized(Class elementClass) {
    return TypeToken.getParameterized(List.class, elementClass).getType();
}

The method getParamterized(), when called during runtime, would return the actual type of the List object along with its element type. Further, this would help the Gson class to convert the JSON array to the exact List object with the correct type information of its elements.

在运行时调用 getParamterized() 方法时,该方法将返回 List 对象的实际类型及其元素类型。此外,这将有助于 Gson 类将 JSON 数组转换为具有正确元素类型信息的 List 对象。

Let’s see the method in action:

让我们看看该方法的实际效果:

@Test
void givenJsonArray_whenListElementTypeDynamic_thenConvertToJavaListUsingGetParameterized() {
    Gson gson = new Gson();
    List<Student> studentsLst = gson.fromJson(jsonArrayOfStudents, getGenericTypeForListFromTypeTokenUsingGetParameterized(Student.class));
    List<School> schoolLst = gson.fromJson(jsonArrayOfSchools, getGenericTypeForListFromTypeTokenUsingGetParameterized(School.class));
    assertAll(
      () -> studentsLst.forEach(e -> assertTrue(e instanceof Student)),
      () -> schoolLst.forEach(e -> assertTrue(e instanceof School))
    );
}

We used the method getGenericTypeForListFromTypeTokenUsingGetParameterized() to get the Type information of List<Student> and List<School>. Finally, using the method fromJson() we converted the JSON arrays successfully to their respective Java List objects.

我们使用方法 getGenericTypeForListFromTypeTokenUsingGetParameterized() 获取了 List<Student>List<School> 的类型信息。最后,我们使用方法 fromJson() 成功地将 JSON 数组转换为各自的 Java List 对象。

4. Solution Using JsonArray

4.使用 JsonArray 的解决方案

The Gson library has a JsonArray class to represent a JSON array. We’ll use it for converting the JSON array into the List object:

Gson 库中有一个 JsonArray 类来表示 JSON 数组。我们将使用它将 JSON 数组转换为 List 对象:

<T> List<T> createListFromJsonArray(String jsonArray, Type elementType) {
    Gson gson = new Gson();
    List<T> list = new ArrayList<>();
    JsonArray array = gson.fromJson(jsonArray, JsonArray.class);
    for(JsonElement element : array) {
        T item = gson.fromJson(element, elementType);
        list.add(item);
    }
    return list;
}

First, we’re converting the JSON array string into the JsonArray object using the usual fromJson() method in the Gson class. Then, we convert each JsonElement element in the JsonArray object to the target Type defined by the second argument elementType in the createListFromJsonArray() method.

首先,我们使用 Gson 类中常用的 fromJson() 方法将 JSON 数组字符串转换为 JsonArray 对象。然后,我们将 JsonArray 对象中的每个 JsonElement 元素转换为 createListFromJsonArray() 方法中第二个参数 elementType 所定义的目标 Type

Each of these converted elements is put into a List and then finally returned at the end.

每个转换后的元素都会被放入一个 List 中,并在最后返回。

Now, let’s see the method in action:

现在,让我们来看看这种方法的实际效果:

@Test
void givenJsonArray_whenListElementTypeDynamic_thenConvertToJavaListUsingJsonArray() {
    List<Student> studentsLst = createListFromJsonArray(jsonArrayOfStudents, Student.class);
    List<School> schoolLst = createListFromJsonArray(jsonArrayOfSchools, School.class);
    assertAll(
      () -> studentsLst.forEach(e -> assertTrue(e instanceof Student)),
      () -> schoolLst.forEach(e -> assertTrue(e instanceof School))
    );
}

We used the method createListFromJsonArray() to successfully convert both the JSON arrays of students and schools to List<Student> and List<School>.

我们使用方法 createListFromJsonArray() 成功地将学生和学校的 JSON 数组转换为 List<Student>List<School>

5. Solution Using TypeToken From Guava

5.使用来自 Guava 的 TypeToken 的解决方案

Similar to the TypeToken class in the Gson library, the TypeToken class in Guava also enables capturing generic types at runtime. Otherwise, this is not possible due to type erasure in Java.

与 Gson 库中的 TypeToken 类类似,Guava 中的 TypeToken也可以在运行时捕获通用类型。否则,由于 Java 中的类型抹除,这是不可能的。

Let’s see an implementation using the Guava TypeToken class:

让我们看看使用 Guava TypeToken 类的实现:

<T> Type getTypeForListUsingTypeTokenFromGuava(Class<T> type) {
    return new com.google.common.reflect.TypeToken<List<T>>() {}
      .where(new TypeParameter<T>() {}, type)
      .getType();
}

The method where() returns a TypeToken object by replacing the type parameter with the class in the variable type.

方法 where() 将类型参数替换为变量 type 中的类,从而返回 TypeToken 对象。

Finally, we can look at it in action:

最后,我们可以看看它的实际效果:

@Test
void givenJsonArray_whenListElementTypeDynamic_thenConvertToJavaListUsingTypeTokenFromGuava() {
    Gson gson = new Gson();
    List<Student> studentsLst = gson.fromJson(jsonArrayOfStudents, getTypeForListUsingTypeTokenFromGuava(Student.class));
    List<School> schoolLst = gson.fromJson(jsonArrayOfSchools, getTypeForListUsingTypeTokenFromGuava(School.class));
    assertAll(
      () -> studentsLst.forEach(e -> assertTrue(e instanceof Student)),
      () -> schoolLst.forEach(e -> assertTrue(e instanceof School))
    );
}

Again, we used the method fromJson() to convert the JSON array to the respective List objects. However, we got the Type object with the help of the Guava library in the method getTypeForListUsingTypeTokenFromGuava().

我们再次使用方法 fromJson() 将 JSON 数组转换为相应的 List 对象。不过,我们借助 Guava 库中的方法 getTypeForListUsingTypeTokenFromGuava() 获得了 Type 对象。

6. Solution Using ParameterizedType of Java Reflection API

6.使用 Java Reflection API 的参数化类型的解决方案

ParameterizedType is an interface that is part of the Java reflection API. It helps represent parameterized types such as Collection<String>.

ParameterizedType 是 Java 反射 API 中的一个接口。它有助于表示参数化类型,如 Collection<String>

Let’s implement ParamterizedType to represent any class that has parameterized types:

让我们实现 ParamterizedType 来表示任何具有参数化类型的类:

public class ParameterizedTypeImpl implements ParameterizedType {
    private final Class<?> rawType;
    private final Type[] actualTypeArguments;

    private ParameterizedTypeImpl(Class<?> rawType, Type[] actualTypeArguments) {
        this.rawType = rawType;
        this.actualTypeArguments = actualTypeArguments;
    }

    public static ParameterizedType make(Class<?> rawType, Type ... actualTypeArguments) {
        return new ParameterizedTypeImpl(rawType, actualTypeArguments);
    }

    @Override
    public Type[] getActualTypeArguments() {
        return actualTypeArguments;
    }

    @Override
    public Type getRawType() {
        return rawType;
    }

    @Override
    public Type getOwnerType() {
        return null;
    }
}

The variable actualTypeArguments would store the class information of the type argument in the generic class, while rawType represents the generic class. The make() method returns the Type object of the parameterized class.

变量 actualTypeArguments 将存储泛型类中类型参数的类信息,而 rawType 则代表泛型类。make() 方法将返回参数化类的 Type 对象。

Finally, let’s see it in action:

最后,让我们看看它的实际效果:

@Test
void givenJsonArray_whenListElementTypeDynamic_thenConvertToJavaListUsingParameterizedType() {
    Gson gson = new Gson();
    List<Student> studentsLst = gson.fromJson(jsonArrayOfStudents, ParameterizedTypeImpl.make(List.class, Student.class));
    List<School> schoolLst = gson.fromJson(jsonArrayOfSchools, ParameterizedTypeImpl.make(List.class, School.class));
    assertAll(
      () -> studentsLst.forEach(e -> assertTrue(e instanceof Student)),
      () -> schoolLst.forEach(e -> assertTrue(e instanceof School))
    );
}

We used the make() method to get the Type information of the parameterized List class and successfully converted the JSON arrays to their respective List object forms.

我们使用 make() 方法获取了参数化 List 类的 Type 信息,并成功地将 JSON 数组转换为各自的 List 对象形式。

7. Conclusion

7.结论

In this article, we discussed four different ways of getting the Type information of a List<T> object during runtime. Finally, we used the Type object for converting the JSON array to a List object using the fromJson() method in the Gson library.

在本文中,我们讨论了在运行时获取 List<T> 对象的 Type 信息的四种不同方法。最后,我们使用 Gson 库中的 fromJson() 方法将 Type 对象用于将 JSON 数组转换为 List 对象。

Since, ultimately, it is the fromJson() method that gets invoked, the performance of all these methods is close to each other. However, the TypeToken.getParamterized() method is the most succinct, so we recommend using it.

由于最终调用的是 fromJson() 方法,因此所有这些方法的性能都很接近。不过,TypeToken.getParamterized() 方法最为简洁,因此我们建议使用该方法。

As usual, the code used is available over on GitHub.

像往常一样,使用的代码可在 GitHub 上获取。