Java Gson How to use TypeToken class to define data type at runtime

Tags: JSON gson Gson fromJson Gson TypeToken

In this Java Gson tutorial we learn how to use the com.google.gson.reflect.TypeToken during deserializing JSON String with Gson library.

How to add Gson to the Java project

To use the Gson library in the Gradle build project, add the following dependency into the build.gradle file.

implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.7'

To use the Gson library in the Maven build project, add the following dependency into the pom.xml file.

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

Or you can download the Gson jar file from Maven Central at gson-2.8.7.jar

To have more information about the Gson library you can visit the project repository at github.com/google/gson

How to use TypeToken class

For example we have Customer and Address classes as below.

Address.java

public class Address {
    private String street;
    private String city;
    private String country;

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }
}

Customer.java

public class Customer {
    private String firstName;
    private String lastName;
    private String email;
    private String website;
    private Address address;

    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 String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getWebsite() {
        return website;
    }

    public void setWebsite(String website) {
        this.website = website;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }
}

In the following Java program we learn how to use TypeToken to provide type information during converting a JSON string into a List of Customer objects.

TypeTokenExample.java

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

import java.lang.reflect.Type;
import java.util.List;

public class TypeTokenExample {
    public static void main(String... args) {
        String jsonString = "[\n" +
                "  {\n" +
                "    \"firstName\": \"Simple\",\n" +
                "    \"lastName\": \"Solution\",\n" +
                "    \"email\": \"contact@simplesolution.dev\",\n" +
                "    \"website\": \"https://simplesolution.dev\",\n" +
                "    \"address\": {\n" +
                "      \"street\": \"Simple Street\",\n" +
                "      \"city\": \"City Name\",\n" +
                "      \"country\": \"Country Name\"\n" +
                "    }\n" +
                "  },\n" +
                "  {\n" +
                "    \"firstName\": \"Java\",\n" +
                "    \"lastName\": \"Tutorial\",\n" +
                "    \"email\": \"java@simplesolution.dev\",\n" +
                "    \"website\": \"https://simplesolution.dev\",\n" +
                "    \"address\": {\n" +
                "      \"street\": \"Test Street\",\n" +
                "      \"city\": \"City Name\",\n" +
                "      \"country\": \"Country Name\"\n" +
                "    }\n" +
                "  },\n" +
                "  {\n" +
                "    \"firstName\": \"Gson\",\n" +
                "    \"lastName\": \"Learn\",\n" +
                "    \"email\": \"gson@simplesolution.dev\",\n" +
                "    \"website\": \"https://simplesolution.dev/tag/gson\",\n" +
                "    \"address\": {\n" +
                "      \"street\": \"Gson Street\",\n" +
                "      \"city\": \"City Name\",\n" +
                "      \"country\": \"Country Name\"\n" +
                "    }\n" +
                "  }\n" +
                "]";

        Gson gson = new Gson();
        Type type = new TypeToken<List<Customer>>(){}.getType();
        List<Customer> customers = gson.fromJson(jsonString, type);

        for(Customer customer : customers) {
            System.out.println("First Name: " + customer.getFirstName());
            System.out.println("Last Name: " + customer.getLastName());
            System.out.println("Email: " + customer.getEmail());
            System.out.println("Website: " + customer.getWebsite());
            System.out.println("Street: " + customer.getAddress().getStreet());
            System.out.println("City: " + customer.getAddress().getCity());
            System.out.println("Country: " + customer.getAddress().getCountry());
            System.out.println();
        }
    }
}
The output is:
First Name: Simple
Last Name: Solution
Email: contact@simplesolution.dev
Website: https://simplesolution.dev
Street: Simple Street
City: City Name
Country: Country Name

First Name: Java
Last Name: Tutorial
Email: java@simplesolution.dev
Website: https://simplesolution.dev
Street: Test Street
City: City Name
Country: Country Name

First Name: Gson
Last Name: Learn
Email: gson@simplesolution.dev
Website: https://simplesolution.dev/tag/gson
Street: Gson Street
City: City Name
Country: Country Name

Happy Coding 😊