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

Convert Map to JSON using Gson library in Java

王林
Release: 2023-09-04 09:41:11
forward
1382 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:
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
Latest Issues
Install JAVA
From 1970-01-01 08:00:00
0
0
0
Unable to install java
From 1970-01-01 08:00:00
0
0
0
Can java be used as the backend of the web?
From 1970-01-01 08:00:00
0
0
0
Is this in Java language?
From 1970-01-01 08:00:00
0
0
0
Help: JAVA encrypted data PHP decryption
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template