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 TypeToken class from com.google.gson.reflect package is used for preserving the generic type information at runtime.

What are Generic Types in Java?

Generic types in Java mean we don't set any method or class to a specific type, like int, String, etc. Instead, we use a type parameter (like T) to represent the type. This allows us to create classes and methods that can operate on objects of different types, and also provides compile-time safety at the same time.

Generic types are a powerful feature of Java that allows us to create classes, interfaces, and methods that operate on a parameterized type. This means we can define a class or method with a placeholder for the type, which can be specified later when we create an instance of the class or call the method.

Example

In this example, T is a type parameter that can be replaced with any type when creating an instance of GenericClass. For example, we can create an instance of GenericClass with Integer or String as the type parameter.

class Box<T> {
   T item;
   void add(T item) {
      this.item = item;
   }
        
   T get() {
      return item;
   }
}

Serializing and Deserializing Generic Types Using Gson?

Gson is developed by Google. It is a Java library that is used for converting Java objects into their JSON representation and vice versa.

By creating an anonymous subclass of TypeToken, we can capture the full generic type and pass it to Gson. This allows Gson to correctly understand and handle the generic types during deserialization.

We need to download the Gson library to use it. Or else, just add a jar file to your project. You can download the jar file from here. If your project is using Maven, add this to your pom.xml file:

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>

Following are the steps to serialize and deserialize generic types using Gson:

  • Add the Gson library to your project.
  • Create a class for the generic type you want to work with.
  • Make a Gson object to handle the conversion.
  • Convert your object to JSON using Gson.
  • Convert the JSON back to your object using Gson.
  • Use TypeToken to keep the generic type info during conversion.
  • Print out the results to see how it works.

Example

In this example, we will create a generic class called Box that can hold any type of object. We will then use Gson to serialize and deserialize an instance of this class.

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class GenericTypeEx{
   public static void main(String[] args) {
      // Create a Gson object
      Gson gson = new Gson();

      // Create a Box object to hold a list of strings
      Box<tring> box = new Box<>();
      List<String> items = new ArrayList<>();
      items.add("Apple");
      items.add("Banana");
      box.setItems(items);

      // Serialize the Box object to JSON
      String json = gson.toJson(box);
      System.out.println("Serialized JSON: " + json);

      // Deserialize the JSON back to a Box object
      Type boxType = new TypeToken<Box<String>>() {}.getType();
      Box<String> deserializedBox = gson.fromJson(json, boxType);
      System.out.println("Deserialized Box: " + deserializedBox.getItems());
   }
}

Following is the output of the above code:

Serialized JSON: {"items":["Apple","Banana"]}
Deserialized Box: [Apple, Banana]
Updated on: 2025-05-12T09:15:57+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements