Java Google Json (Gson) Serializing Generics

Serializing list

As we saw in the previous tutorial serializing and deserializing classes with generic types is non trivial since generic type information is lost while serializing. Gson provides a class called to store generic types. The example below shows how to use the TypeToken class to serialize and deserialize Classes with generic types.

package com.studytrails.json.gson;

import java.lang.reflect.Type;


public class GenericTypesExample8 {
	public static void main(String[] args) {
		// create an animal class that is of type dog.
		Animal animal = new Animal<Dog>();
		// Create a Dog instance
		Dog dog = new Dog("I am a dog");

		Gson gson = new Gson();
		// Define a Type that is an Animal of type dog.
		Type animalType = new TypeToken<Animal<Dog>>() {

		// we first convert the animal object to a json and then read the json
		// back. However we define the json to be of Animal type
		Animal animal1 = gson.fromJson(gson.toJson(animal, animalType), Animal.class);
		System.out.println(animal1.get().getClass()); // prints class

		// In contrast to above where we read the json back using the Animal
		// type, here we read the json back as the custom animalType Type. This
		// gives Gson an idea of what
		// the generic type should be.
		Animal animal2 = gson.fromJson(gson.toJson(animal), animalType);
		// prints class com.studytrails.json.gson.Dog



Animal class

package com.studytrails.json.gson;

public class Animal {

	public T animal;

	public void setAnimal(T animal) {
		this.animal = animal;

	public T get() {
		return animal;



Dog Class

package com.studytrails.json.gson;

public class Dog {
	private String name;

	public Dog(String name) { = name;

	public String getName() {
		return name;


Leave a Reply

Your email address will not be published. Required fields are marked *