Convert a Map to JSON using the Gson library in Java?

A Gson is a library that can be used to parse Java objects to JSON and vice-versa. It can also be used to convert a JSON string to an equivalent Java object. In order to parse java object to JSON or JSON to java object, we need to import package in our Java program.

We can create a Gson instance in two ways

  • By using new Gson().
  • By creating a GsonBuilder instance and calling with the create() method.

In the below program, we can convert a Map to a JSON object.


import java.lang.reflect.*;
import java.util.*;
public class ConverMapToJsonTest {
   public static void main(String args[]) {
      SortedMap<String, String> data= new TreeMap<String, String>();
      data.put("Raja", "Java");
      data.put("Ravi", "SAP");
      data.put("Surya", "Python");
      data.put("Kiran", "Scala");
      data.put("Vamsi", "Selenium");
      Gson gson = new Gson();
      Type gsonType = new TypeToken(){}.getType();
      String gsonString = gson.toJson(data, gsonType);



Updated on: 04-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started