JSON is a lightweight , text based and language agnostic >Data exchange format. JSON can represent two structured types, such as object and array. An object is an unordered collection of key /value pairs, and an array is an ordered sequence of values.
We can use the toJSONString() method to convert the Map into a JSON object ( >static) ##org.json.simple.JSONValue. It has two important static methods: writeJSONString()The method encodes the object into JSON text and writes it out, escape()The method escapes special characters and Meaningful quotation marks, \, /, \r, \n, \b, \f, \t.
Exampleimport 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); } }
{"1":"India","2":"Australia","3":"England","4":"South Africa"}
The above is the detailed content of How can we convert map to JSON object in Java?. For more information, please follow other related articles on the PHP Chinese website!