Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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.
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"} Advertisements
