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>20240303</version>
</dependency>
</dependencies>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024