Home  >  Article  >  Java  >  Convert Map to JSON using Gson library in Java

Convert Map to JSON using Gson library in Java

王林
王林forward
2023-09-04 09:41:111288browse

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

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

In the following program, we can map to JSON objects.

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"}

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete