
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert a Map to JSON Using the Gson Library in Java
Converting a map to a JSON object is our task here. Let's see how to convert a map to a JSON object in Java using the Gson library.
Converting a Map to JSON using the Gson library
JSON is a simple and lightweight data interchange format. It stores data in key-value pairs. A map is also a collection of key-value pairs. So, we can easily convert a map to a JSON object. If you are not familiar with JSON, refer JSON. And if you want to know more about Map, refer Map.
Gson is developed by Google. It is an external library, which means not included in Java standard library by default. It is used for converting Java objects to JSON and vice versa. We will use toJson() method of Gson class to convert a map to JSON.
We cannot use the Gson library without downloading or adding it to the project. Because it is not a part of the Java standard library. But we can still use the Gson library without downloading it. We can use it from the Maven repository. Let's see how to add Gson library to our project:
- First, we need to add the Gson library to our project. If you are using Maven, add this to your
pom.xml
file:<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.9</version> </dependency>
- If you are not using Maven, add a jar file to your project. You can download the jar file from here.
Steps to convert a map to JSON using the Gson library:
- First, import the Gson library as discussed above.
- Then create a map of strings.
- Then we will create an instance of Gson class.
- Next, we will convert the map to JSON using the toJson() method of Gson.
- Finally, we will print the JSON string.
Example to convert Map to JSON
The following is the code to convert a map to JSON using the Gson library:
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.HashMap; import java.util.Map; public class MapToJson { public static void main(String[] args) { // Create a map of strings Map<String, String> map = new HashMap<>(); map.put("Name", "Ansh"); map.put("Age", "22"); map.put("Salary", "10000000.00"); map.put("IsSelfEmployee", "false"); // Create a Gson instance Gson gson = new GsonBuilder().setPrettyPrinting().create(); // Convert the map to JSON String json = gson.toJson(map); // Print the JSON string System.out.println(json); } }
Following is the output of the above code:
{ "Name": "Ansh", "Age": "22", "Salary": "10000000.00", "IsSelfEmployee": "false" }