GSON - Serializing and Deserializing Generic Types

In this quick article, we will see how to serialize and deserialize a generic class using GSON. Generic type information is lost while serializing because of Java Type Erasure. You can solve this problem by specifying the correct parameterized type for your generic type. Gson provides this with the TypeToken class.

GSON Maven Dependency

To use Gson with Maven2/3, you can use the Gson version available in Maven Central by adding the following dependency:
<dependencies>
    <!--  Gson: Java to Json conversion -->
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.5</version>
      <scope>compile</scope>
    </dependency>
</dependencies>
Let's create Box generic class and we will use it in upcoming examples:
class Box < T > {
    private T t;

    public void set(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }
}
Let's create a User POJO class:
package net.javaguides.gson;

public class User {

    private int id;
    private String firstName;
    private String lastName;
    private int age;
    private String gender;
    private String password;

    public int getId() {
        return id;
    }

    public void setId(int i) {
        this.id = i;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + ", gender=" +
            gender + "]";
    }
}

Serializing and Deserializing Generic Types Example

package net.javaguides.gson;

import java.lang.reflect.Type;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class GSONGenericsExample {
    public static void main(String[] args) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();

        Box < User > type2 = new Box < > ();
        User user = new User();
        user.setId(100);
        user.setFirstName("Ramesh");
        user.setLastName("Fadatare");
        user.setGender("Male");
        user.setAge(28);
        type2.set(user);

        // Serialization of generic User type to json

        Type fooType2 = new TypeToken < Box < User >> () {}.getType();
        String userJson = gson.toJson(type2, fooType2);
        System.out.println(userJson);

        //  De-serialization of generic User type to json
        Box < User > box = gson.fromJson(userJson, fooType2);
        System.out.println(box.get().toString());
    }
}

class Box < T > {
    private T t;

    public void set(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }
}
Output:
{
  "t": {
    "id": 100,
    "firstName": "Ramesh",
    "lastName": "Fadatare",
    "age": 28,
    "gender": "Male"
  }
}
User [id=100, firstName=Ramesh, lastName=Fadatare, age=28, gender=Male]

Reference

Comments