Pretty Print JSON Using org.json Library in Java



Pretty Printing JSON using "org.json" Library

Pretty printing something means formatting it in a way that is easy to read, understand, and also looks good. Here we will format JSON data in a good-looking as well as readable way. We will be using the org.json library to pretty print JSON data in Java.

The method toString(int indentFactor) of the JSONObject class is used to pretty print JSON data. The indentFactor parameter specifies the number of spaces to add for each level of indentation.

To use the org.json library, we need to add it to our project. If you are using Maven, add this to your pom.xml file:

<dependency>
   <groupId>org.json</groupId>
   <artifactId>json</artifactId>
   <version>20210307</version>
</dependency>

If you are not using Maven, you can download the jar file from here. Following are the steps to pretty print JSON data in Java:

  • First, import the org.json library.
  • Then create a JSON string that you want to pretty print.
  • Next, create a JSONObject object using the JSON string.
  • Then call the toString(int indentFactor) method of the JSONObject object to pretty print the JSON data.
  • Finally, print the pretty printed JSON data.

Example

Following is the code to pretty print JSON data in Java:

import org.json.JSONObject;
import org.json.JSONException;

public class PrettyPrintJsonExample {
   public static void main(String[] args) {
      // Create a JSON string
      String jsonString = "{"name":"Ansh", "age":23, "city":"Delhi"}";
      // Create a JSONObject object using the JSON string
      JSONObject jsonObject = new JSONObject(jsonString);
      // Pretty print the JSON data with an indent factor of 4 spaces
      String prettyJson = jsonObject.toString(4);
      // Print the pretty printed JSON data
      System.out.println(prettyJson);
   }
}

Following is the output of the above code:

{
   "name": "Ansh",
   "age": 23,
   "city": "Delhi"
}
Updated on: 2025-05-12T11:06:55+05:30

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements