- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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"}
- Related Articles
- How can we convert a JSON string to a JSON object in Java?
- How to convert a Map to JSON object using JSON-lib API in Java?
- How can we encode a JSON object in Java?
- How can we decode a JSON object in Java?
- How can we convert a list to the JSON array in Java?
- How can we parse a nested JSON object in Java?
- Convert a Map to JSON using the Gson library in Java?
- How to map the JSON data with Jackson Object Model in Java?
- How to convert the JSON object to a bean using JSON-lib API in Java?
- How can we convert a JSON array to a list using Jackson in Java?\n
- Convert JSON to/from Map using Jackson library in Java?
- Convert a JSON String to Java Object using the json-simple library in Java?\n
- How to convert a JSON to Java Object using the Jackson library in Java?\n
- Convert a JSON object to XML format in Java?\n
- How to convert Java object to JSON using GSON library?

Advertisements