How can we convert a map to the JSON object in Java?

The JSON is a lightweight, text-based and language-independent data exchange format. The JSON can represent two structured types like objects and arrays. An object is an unordered collection of key/value pairs and an array is an ordered sequence of values

We can convert a Map to JSON object using the toJSONString() method(static) of org.json.simple.JSONValue. It has two important static methods: writeJSONString() method to encode an object into JSON text and write it out, escape() method to escape the special characters and escape quotes, \, /, \r, \n, \b, \f, \t.


import java.util.*;
import org.json.simple.JSONValue;
public class ConvertMapJSONTest {
   public static void main(String[] args) {
      Map<String, Object> map = new HashMap<String, Object>();
      map.put("1", "India");
      map.put("2", "Australia");
      map.put("3", "England");
      map.put("4", "South Africa");
      String jsonStr = JSONValue.toJSONString(map); // converts Map to JSON


{"1":"India","2":"Australia","3":"England","4":"South Africa"}

Updated on: 04-Jul-2020

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started