Home >Java >javaTutorial >Convert Map to JSON using Gson library in Java
Gson is a library that can be used to parse Java objects to JSON and vice versa. It can also be used to convert JSON strings into equivalent Java objects. In order to parse java objects to JSON or JSON to java objects, we need to import the com.google.gson package in our Java program.
We can create Gson instances in two ways
In the following program, we can map to JSON objects.
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); } }
{"Kiran":"Scala","Raja":"Java","Ravi":"SAP","Surya":"Python","Vamsi":"Selenium"}
The above is the detailed content of Convert Map to JSON using Gson library in Java. For more information, please follow other related articles on the PHP Chinese website!