How to convert hashmap to json in Java?

In this tutorial I will explains you Java code for converting a map object to its JSON string representation.

How to convert hashmap to json in Java?

This example on roseindia.net shows you the code for converting Hash Map object to JSON String using Google Gson library. We have also provides the instruction in video titled "How to convert hashmap to json in Java?" where you can see the actual running example code.

How to convert hashmap to json in Java?

You can also write Java code for creating the JSON String yourself but its time consuming process and may end up with bugs. So, its better to use the pre-developed library for converting the Map object or any other Java object to its JSON string.

One of the best library is the Google Gson library which you can use while working with JSON in Java. In this tutorial we have just used this for converting the map to string in Java.

Gson (google-gson) is an open source library in Java for mapping the Java objects to JSON representation and vice-versa. If you have pre-compiled Java library and you have created objects of the classes from the library you can still use the Gson for converting its object to JSON and vice-versa. This library does not need the actual source code of any Java object to work with. So, its good library for JSON processing.

How to convert hashmap to json in Java?

Example code:

Here is the Map object for converting into JSON:

Map map = new HashMap();
map.put("name", "Deepak Kumar");
map.put("web", "http://www.roseindia.net");

Video: How to convert hashmap to json in Java?

Code for converting the Map into JSON:

Gson gson = new GsonBuilder().disableHtmlEscaping().create();
String jsonString = gson.toJson(map);
System.out.println(jsonString);

Full example:

Following the code code of the complete program:

package net.roseindia;

import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class MapToJSON {

	public static void main(String[] args) {
		Map map = new HashMap();
		map.put("name", "Deepak Kumar");
		map.put("web", "http://www.roseindia.net");

		Gson gson = new GsonBuilder().disableHtmlEscaping().create();
		String jsonString = gson.toJson(map);
		System.out.println(jsonString);

	}

}

You should add following Gson maven dependency in the pom.xml file of your project:

<dependency>
	<groupId>com.google.code.gson</groupId>
	<artifactId>gson</artifactId>
	<version>2.2.4</version>
</dependency>

Example output:

After running the above example you will get following JSON as output:

{"web":"http://www.roseindia.net","name":"Deepak Kumar"}

In this tutorial your leaned the usage of Google Gson library for converting Map into JSON.

Check more tutorials of JSON Programming on roseindia.net.