Home > Java > javaTutorial > body text

How to serialize and deserialize generic types using Gson library in Java?

WBOY
Release: 2023-09-10 09:17:02
forward
695 people have browsed it

How to serialize and deserialize generic types using Gson library in Java?

If a Java class is a generic type and we are using it with the Gson library for JSON serialization and deserialization. The Gson library provides a class called com.google.gson.reflect.TypeToken to store generic types by creating a Gson TypeToken class and pass the class type. Using this type, Gson can able to know the class passed in the generic class.

Syntax

public class TypeToken<T> extends java.lang.Object
Copy after login

Example

import java.lang.reflect.Type;
import java.util.*;
import com.google.gson.*;
import com.google.gson.reflect.*;
public class GenericTypesJSONTest {
   public static void main(String[] args) {
      Gson gson = new GsonBuilder().setPrettyPrinting().create();
      List<String> list = Arrays.asList("INDIA", "AUSTRALIA", "ENGLAND", "SOUTH AFRICA");
      String jsonStr = gson.toJson(list);
      System.out.println(jsonStr);
      Type listType = new TypeToken<List<String>>() {}.getType();
      list = gson.fromJson(jsonStr, listType);
      System.out.println(list);
   }
}
Copy after login

输出

[
   "INDIA",
   "AUSTRALIA",
   "ENGLAND",
   "SOUTH AFRICA"
]
[INDIA, AUSTRALIA, ENGLAND, SOUTH AFRICA]
Copy after login

The above is the detailed content of How to serialize and deserialize generic types using Gson library in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
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