Home > Java > javaTutorial > How to Use Gson TypeToken with Dynamic ArrayList Item Types at Runtime?

How to Use Gson TypeToken with Dynamic ArrayList Item Types at Runtime?

Patricia Arquette
Release: 2024-12-05 17:16:11
Original
358 people have browsed it

How to Use Gson TypeToken with Dynamic ArrayList Item Types at Runtime?

Gson TypeToken with Dynamic ArrayList Item Type at Runtime

When working with JSON, it's common to convert JSON data into typed objects using Gson. However, you may encounter a scenario where the type of ArrayList item you need to parse is determined dynamically at runtime using reflection. In such cases, the traditional TypeToken approach may fall short.

For instance, consider this code:

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

This code converts a JSON string into a list of myClass objects. But what if the item type of the ArrayList should be determined dynamically?

To achieve this, you can leverage a new feature introduced in Gson version 2.8.0: TypeToken.getParameterized. This method allows you to create a TypeToken with a specified parameterized type.

Here's how you can use it:

private <T> Type setModelAndGetCorrespondingList2(Class<T> type) {
    Type typeOfObjectsListNew = TypeToken.getParameterized(ArrayList.class, type).getType();
    return typeOfObjectsListNew;
}
Copy after login

By passing the ArrayList class and the dynamic item type class type as arguments to TypeToken.getParameterized, you create a TypeToken that represents an ArrayList with the desired item type. This TypeToken can then be used as the parameter for Gson.fromJson to correctly parse the JSON data into the desired list type.

The above is the detailed content of How to Use Gson TypeToken with Dynamic ArrayList Item Types at Runtime?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template