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 !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

3 thoughts on “Gson – Serialize and deserialize HashMap containing custom objects”

  1. Hi, i want to learn how to serialize a class who contains a HashMap which contains an ArrayList. Something like that;

    HashMap<String, ArrayList> map;

    May you show me right way to do this.
    Thank you in advance.

    Reply
  2. My question is how to serialize a class who contains a HashMap as attribut.
    For example :

    public class Entreprise {
    
         private HashMap<Integer, Employee> employees;
    
    }
    

    When i tired to serialize a class like that it saves the Employee object’s adress and not as it should be.
    So i’im trying to create a custom serializer. I’m stucked, some help would be appreciated.
    Have a nice day.

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.