In the previous example we use JSONObject
to directly put key-value pairs to create JSON string, using the various put()
methods. Instead of doing that, we can also create JSON from a Map
object. We create a Map
with some key-value pairs in it, and pass it as an argument when instantiating a JSONObject
.
These are the steps for creating JSON from a Map
:
- Create a
Map
object using aHashMap
class. - Put some key-value pairs into the
map
object. - Create a
JSONObject
and pass themap
as argument to its constructor. - Print the
JSONObject
, we callobject.toString()
to get the JSON string.
Let’s try the following code snippet.
package org.kodejava.json;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class JSONFromMap {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("id", "1");
map.put("name", "Alice");
map.put("age", "20");
JSONObject object = new JSONObject(map);
System.out.println(object);
}
}
Running this code produces the following output:
{"name":"Alice","age":"20","id":"1"}
Maven Dependencies
<dependencies>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20230618</version>
<type>bundle</type>
</dependency>
</dependencies>
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023