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

JavaJSONObject Oriented ProgrammingProgramming

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.

Example

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
      System.out.println(jsonStr);
   }
}

Output

{"1":"India","2":"Australia","3":"England","4":"South Africa"}
raja
Published on 17-Sep-2019 11:12:53
Advertisements