Home > Java > javaTutorial > body text

Convert Map to JSON using Gson library in Java

王林
Release: 2023-09-04 09:41:11
forward
1299 people have browsed it

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);
   }
}
Copy after login

Output

{"Kiran":"Scala","Raja":"Java","Ravi":"SAP","Surya":"Python","Vamsi":"Selenium"}
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template