Home > Java > javaTutorial > body text

How can we convert map to JSON object in Java?

PHPz
Release: 2023-08-26 08:53:16
forward
1124 people have browsed it

How can we convert map to JSON object in Java?

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.

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);
   }
}
Copy after login

Output

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

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!