Gson – Serialize and deserialize HashMap containing custom objects

Learn to serialize HashMap using Google Gson library. Also learn to deserialize JSON string to HashMap containing custom Objects using Gson such that field values are copied into appropriate generic types.

These conversion can be used to create deep clone of HashMap.

1. Serialize HashMap containing generic types to JSON

Serializing a hashmap to JSON using Gson is easy process. Just use gson.toJson() method to get the JSON string after converting HashMap.

Java program to convert HashMap to JSON string using Gson.

HashMap<Integer, Employee> employeeMap = new HashMap<>();
        
employeeMap.put(1, new Employee(1l, "Alex", LocalDate.of(1990, 01, 01)));
employeeMap.put(2, new Employee(2l, "Bob", LocalDate.of(1990, 02, 01)));

//Deep clone
Gson gson = new Gson();
String jsonString = gson.toJson(employeeMap);
{
  "1": {
    "id": 1,
    "name": "Alex",
    "dob": {
      "year": 1990,
      "month": 1,
      "day": 1
    }
  },
  "2": {
    "id": 2,
    "name": "Bob",
    "dob": {
      "year": 1990,
      "month": 2,
      "day": 1
    }
  }
}

Here the Employee class is given as:

import java.time.LocalDate;

public class Employee implements Comparable<Employee>{

    private Long id;
    private String name;
    private LocalDate dob;

    public Employee(Long id, String name, LocalDate dob) {
        super();
        this.id = id;
        this.name = name;
        this.dob = dob;
    }
    
    @Override
    public int compareTo(Employee o) {
        return this.getId().compareTo(o.getId());
    }

    //Getters and setters

    @Override
    public String toString() {
        return "Employee [id=" + id + ", name=" + name + ", dob=" + dob + "]";
    }
}

2. Convert JSON to HashMap containing custom objects

To deserialize JSON string back to HashMap involve two steps:

  1. Create com.google.gson.reflect.TypeToken which represents a generic type. It forces clients to create a subclass of this class which enables retrieval the type information even at runtime.
  2. Use gson.fromJson() method to get HashMap from JSON string.

Java program to parse JSON to HashMap object containing generic types.

import java.lang.reflect.Type;
import java.time.LocalDate;
import java.util.HashMap;

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

public class GsonExample 
{
    public static void main(String[] args) 
    {
        HashMap<Integer, Employee> employeeMap = new HashMap<>();
        
        employeeMap.put(1, new Employee(1l, "Alex", LocalDate.of(1990, 01, 01)));
        employeeMap.put(2, new Employee(2l, "Bob", LocalDate.of(1990, 02, 01)));
        
        //Deep clone
        Gson gson = new Gson();
        String jsonString = gson.toJson(employeeMap);
        
        Type type = new TypeToken<HashMap<Integer, Employee>>(){}.getType();
        HashMap<Integer, Employee> clonedMap = gson.fromJson(jsonString, type); 
        
        System.out.println(clonedMap);
    }
}
{1=Employee [id=1, name=Alex, dob=1990-01-01], 2=Employee [id=2, name=Bob, dob=1990-02-01]}

Happy Learning !!

Leave a Reply

3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.