How do I pretty print JSON string in JSON-Java?

In JSON-Java we can make a pretty-printed JSON string by specifying an indentFactor to the JSONObject‘s toString() method. The indent factor is the number of spaces to add to each level of indentation.

If indentFactor > 0 and the JSONObject has only one key, the JSON string will be printed a single line, and if the JSONObject has 2 or more keys, the JSON string will be printed in multiple lines.

Let’s create a pretty-printed JSONObject text using the code below.

package org.kodejava.json;

import org.json.JSONArray;
import org.json.JSONObject;

public class PrettyPrintJSON {
    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", 1L);
        jsonObject.put("name", "Alice");
        jsonObject.put("age", 20);
        JSONArray courses = new JSONArray(
                new String[]{"Engineering", "Finance"});
        jsonObject.put("courses", courses);

        // Default print without indent factor
        System.out.println(jsonObject);

        // Pretty print with 2 indent factor
        System.out.println(jsonObject.toString(2));
    }
}

Running this code produces the following output:

{"courses":["Engineering","Finance"],"name":"Alice","id":1,"age":20}
{
  "courses": [
    "Engineering",
    "Finance"
  ],
  "name": "Alice",
  "id": 1,
  "age": 20
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20230618</version>
        <type>bundle</type>
    </dependency>
</dependencies>

Maven Central

Wayan

Leave a Reply

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