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

JavaJSONObject Oriented ProgrammingProgramming

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 com.google.gson 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.

Example

import java.lang.reflect.*;
import java.util.*;
import com.google.gson.*;
import com.google.gson.reflect.*;
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);
      System.out.println(gsonString);
   }
}

Output

{"Kiran":"Scala","Raja":"Java","Ravi":"SAP","Surya":"Python","Vamsi":"Selenium"}
raja
Published on 20-Sep-2019 10:46:32
Advertisements