How do I create JSON from a Map?

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 a HashMap class.
  • Put some key-value pairs into the map object.
  • Create a JSONObject and pass the map as argument to its constructor.
  • Print the JSONObject, we call object.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>

Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.