GSON - Serialize and Deserialize Collections Example

In this quick article, we will use GSON to serialize and deserialize collections. In this example, we serialize a collection of Integer and Employee objects into JSON representation and using the TypeToken to deserialize the collection of Integers into the arbitrary Java Object.

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>

Serialize Collection of Employees

Let's first create an Employee POJO class:
class Employee {
    private String firstName;
    private String lastName;
    public Employee(String firstName, String lastName) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
    }
}
Now, let's write a code to serialize a collection of employee objects:
Gson gson = new Gson();
// Serialization of collection of employees
Collection<Employee> employees = Arrays.asList(new Employee("firstName1", "lastName1"),
  new Employee("firstName2", "lastName2"),
  new Employee("firstName3", "lastName3"),
  new Employee("firstName4", "lastName4"),
  new Employee("firstName5", "lastName5"));

String empJson = gson.toJson(employees); 
System.out.println(empJson);

Deserialize Collection of Employees

// De-serialization of employee json to Collection of employee Java objects
String employeeJson = "[\r\n" + 
  "  {\r\n" + 
  "    \"firstName\": \"firstName1\",\r\n" + 
  "    \"lastName\": \"lastName1\"\r\n" + 
  "  },\r\n" + 
  "  {\r\n" + 
  "    \"firstName\": \"firstName2\",\r\n" + 
  "    \"lastName\": \"lastName2\"\r\n" + 
  "  },\r\n" + 
  "  {\r\n" + 
  "    \"firstName\": \"firstName3\",\r\n" + 
  "    \"lastName\": \"lastName3\"\r\n" + 
  "  },\r\n" + 
  "  {\r\n" + 
  "    \"firstName\": \"firstName4\",\r\n" + 
  "    \"lastName\": \"lastName4\"\r\n" + 
  "  },\r\n" + 
  "  {\r\n" + 
  "    \"firstName\": \"firstName5\",\r\n" + 
  "    \"lastName\": \"lastName5\"\r\n" + 
  "  }\r\n" + 
  "]";
Type type = new TypeToken<Collection<Employee>>() {}.getType();
Collection<Employee> collectionOfEmp = gson.fromJson(employeeJson, type);
System.out.println(collectionOfEmp);
Let's see one more example, serialize and deserialize collection of Integers.

Serialize and Deserialize Collections of Integer

Gson gson = new GsonBuilder().setPrettyPrinting().create();
Collection<Integer> ints = Arrays.asList(1, 2, 3, 4, 5);

// Serialization of integer
String json = gson.toJson(ints); 
System.out.println(json);

// Deserialization of integer
Type collectionType = new TypeToken<Collection<Integer>>() {}.getType();
Collection<Integer> ints2 = gson.fromJson(json, collectionType);
System.out.println(ints2);

Complete Program for Reference

package net.javaguides.gson;

import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collection;

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

public class GSONCollectionsExample {
    public static void main(String[] args) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        Collection < Integer > ints = Arrays.asList(1, 2, 3, 4, 5);

        // Serialization of integer
        String json = gson.toJson(ints);
        System.out.println(json);

        // Serialization of collection of employees
        Collection < Employee > employees = Arrays.asList(new Employee("firstName1", "lastName1"),
            new Employee("firstName2", "lastName2"),
            new Employee("firstName3", "lastName3"),
            new Employee("firstName4", "lastName4"),
            new Employee("firstName5", "lastName5"));

        String empJson = gson.toJson(employees);
        System.out.println(empJson);


        // Deserialization of integer
        Type collectionType = new TypeToken < Collection < Integer >> () {}.getType();
        Collection < Integer > ints2 = gson.fromJson(json, collectionType);
        System.out.println(ints2);

        // De-serialization of employee json to Collection of employee Java objects
        String employeeJson = "[\r\n" +
            "  {\r\n" +
            "    \"firstName\": \"firstName1\",\r\n" +
            "    \"lastName\": \"lastName1\"\r\n" +
            "  },\r\n" +
            "  {\r\n" +
            "    \"firstName\": \"firstName2\",\r\n" +
            "    \"lastName\": \"lastName2\"\r\n" +
            "  },\r\n" +
            "  {\r\n" +
            "    \"firstName\": \"firstName3\",\r\n" +
            "    \"lastName\": \"lastName3\"\r\n" +
            "  },\r\n" +
            "  {\r\n" +
            "    \"firstName\": \"firstName4\",\r\n" +
            "    \"lastName\": \"lastName4\"\r\n" +
            "  },\r\n" +
            "  {\r\n" +
            "    \"firstName\": \"firstName5\",\r\n" +
            "    \"lastName\": \"lastName5\"\r\n" +
            "  }\r\n" +
            "]";
        Type type = new TypeToken < Collection < Employee >> () {}.getType();
        Collection < Employee > collectionOfEmp = gson.fromJson(employeeJson, type);
        System.out.println(collectionOfEmp);
    }
}

class Employee {
    private String firstName;
    private String lastName;
    public Employee(String firstName, String lastName) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
    }
}
Output:
[
  1,
  2,
  3,
  4,
  5
]
[
  {
    "firstName": "firstName1",
    "lastName": "lastName1"
  },
  {
    "firstName": "firstName2",
    "lastName": "lastName2"
  },
  {
    "firstName": "firstName3",
    "lastName": "lastName3"
  },
  {
    "firstName": "firstName4",
    "lastName": "lastName4"
  },
  {
    "firstName": "firstName5",
    "lastName": "lastName5"
  }
]
[1, 2, 3, 4, 5]
[net.javaguides.gson.Employee@1698c449, net.javaguides.gson.Employee@5ef04b5, net.javaguides.gson.Employee@5f4da5c3, net.javaguides.gson.Employee@443b7951, net.javaguides.gson.Employee@14514713]

Collections Limitations

Gson can serialize a collection of arbitrary objects but can not deserialize from it, because there is no way for the user to indicate the type of the resulting object. Instead, while deserializing, the Collection must be of a specific, generic type. This makes sense and is rarely a problem when following good Java coding practices.

Reference

Comments