Gson – Serialize and Deserialize a Map

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 conversions can be used to create deep cloning of the HashMap.

1. Maven

Include the latest version of Gson into the project runtime.

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

2. Serializing a Map

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

Java program to convert HashMap to JSON string using Gson.

Map map = Map.of(
    1, new User(1L, "lokesh", "gupta", LocalDate.of(1999, Month.JANUARY, 1), new Department(1, "IT", true)),
    2, new User(2L, "alex", "gussin", LocalDate.of(1988, Month.MARCH, 31), new Department(2, "FINANCE", true)));

Gson gson = new GsonBuilder()
    .registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
    .create();

String jsonString = gson.toJson(map);

System.out.println(jsonString);

The program output.

{
  "2": {
    "id": 2,
    "firstName": "alex",
    "lastName": "gussin",
    "dateOfbirth": "1988-03-31",
    "department": {
      "id": 2,
      "name": "FINANCE",
      "active": true
    }
  },
  "1": {
    "id": 1,
    "firstName": "lokesh",
    "lastName": "gupta",
    "dateOfbirth": "1999-01-01",
    "department": {
      "id": 1,
      "name": "IT",
      "active": true
    }
  }
}

Here the User and Department classes are given as:

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class User {

  private Long id;
  private String firstName;
  private String lastName;
  private LocalDate dateOfbirth;
  private Department department;
}

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Department {

  private Integer id;
  private String name;
  private boolean active;
}

3. Deserializing a Map

To deserialize JSON string back to HashMap involves two steps:

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

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

Gson gson = new GsonBuilder()
    .registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
    .create();

Type mapType = new TypeToken<HashMap<Integer, User>>(){}.getType();

HashMap<Long, User> usersMap = gson.fromJson(jsonString, mapType);

System.out.println(usersMap);

The program output.

{1=User(id=1, firstName=lokesh, lastName=gupta, dateOfbirth=1999-01-01, department=Department(id=1, name=IT, active=true)), 
2=User(id=2, firstName=alex, lastName=gussin, dateOfbirth=1988-03-31, department=Department(id=2, name=FINANCE, active=true))}

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
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.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode