HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Gson / Gson – Serialize and deserialize HashMap containing custom objects

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?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Melek

    February 18, 2020

    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.

  2. Reda

    September 9, 2019

    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.

    • Lokesh Gupta

      September 9, 2019

      I will check and reply.

Comments are closed on this article!

Search Tutorials

Gson Tutorial

  • Gson – Introduction
  • Gson – Installation
  • GSON – (De)serialize JSON
  • Gson – Pretty Printing
  • GSON – Array
  • GSON – Set
  • Gson – Map
  • Gson – GsonBuilder
  • Gson – NULL values
  • Gson – Version Support
  • Gson – @SerializedName
  • Gson – Ignore fields
  • Gson – JsonReader
  • Gson – JsonParser
  • Gson – Custom (De)serialization
  • Gson – Quick Guide

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces