Home > Java > javaTutorial > How to Deserialize a Generic List with Gson?

How to Deserialize a Generic List with Gson?

DDD
Release: 2024-12-15 06:09:14
Original
936 people have browsed it

How to Deserialize a Generic List with Gson?

Deserializing a Generic List with Gson

When using Gson to transfer a list object, you may encounter challenges when dealing with generic types. This article provides a comprehensive guide to deserializing generic lists with Gson.

Problem:
Attempting to deserialize a list using new List().getClass() results in an error or a complex fix with numerous method stubs.

Solution:
To correctly deserialize a generic list, employ the TypeToken class as follows:

Type listType = new TypeToken<List<MyClass>>() {}.getType();
MyClass mc = new Gson().fromJson(result, listType);
Copy after login

This approach eliminates the need for the getClass() invocation, providing a more concise and effective solution.

Explanation:
TypeToken captures the generic type at compile time. The anonymous subclass created during instantiation ensures that the correct type information is maintained when passed to Gson's fromJson method. This ensures proper deserialization of your generic list.

Additional Notes:

  • The Type object can represent any Java type, including parameterized instantiations of generic types, overcoming type erasure limitations.
  • TypeToken must capture types fully known at compile time; it cannot capture generic type parameters (new TypeToken>() {}.getType() is not allowed).
  • For进一步了解如何使用 TypeToken 类,请参阅其文档。

The above is the detailed content of How to Deserialize a Generic List with Gson?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template