JSON pretty printing in Java

When working with JSON data, readability matters. JSON pretty printing is a technique used to format JSON data in a human-readable manner, making it easier to analyze, debug, and understand. In this tutorial, we’ll explore how to perform JSON pretty printing in Java, leveraging libraries to format JSON for improved readability.

The Issue

By default if you run a toString() of a javax.json.JsonObject the output will be a rough JSON with no indentation. For example:

{"orderId":12345678,"orderDate":"2023-10-04","orderStatus":"Pending","orderDetails":{"shippingAddress":{"street":"123 Main Street","city":"Anytown","state":"CA","zipCode":"90210"}},"orderItems":[{"productId":1001,"productName":"Laptop","quantity":2,"unitPrice":1000},{"productId":1002,"productName":"Mouse","quantity":1,"unitPrice":50}]}

How to indent the JSON File

There are several libraries available to create JSON from Java. If you rely on the jakarta.json ( formerly javax.json ) libraries, then you can simply create a JsonWriter setting the property JsonGenerator.PRETTY_PRINTING .

For example, the following Java main class shows how to create a JSON from Java using a jakarta.json.JsonObject:

//usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS jakarta.json:jakarta.json-api:2.0.2
//DEPS org.glassfish:jakarta.json:2.0.1

import jakarta.json.Json;
import jakarta.json.JsonObject;
import jakarta.json.JsonWriter;
import jakarta.json.stream.JsonGenerator;

import java.io.StringWriter;
import java.util.Collections;

public class JSONPrettyFormat {
    public static void main(String[] args) {

        JsonObject jsonObject = Json.createObjectBuilder()
        .add("orderId", 12345678)
        .add("orderDate", "2023-10-04")
        .add("orderStatus", "Pending")
        .add("orderDetails", Json.createObjectBuilder()
                .add("shippingAddress", Json.createObjectBuilder()
                        .add("street", "123 Main Street")
                        .add("city", "Anytown")
                        .add("state", "CA")
                        .add("zipCode", "90210"))
        .add("orderItems", Json.createArrayBuilder()
                        .add("productId", 1001)
                        .add("productName", "Laptop")
                        .add("quantity", 2)
                        .add("unitPrice", 1000))
                        .add("productId", 1002)
                        .add("productName", "Mouse")
                        .add("quantity", 1)
                        .add("unitPrice", 50))
        // Get the JSON string from the JSONObject
        // Create a StringWriter to store the formatted JSON
        StringWriter stringWriter = new StringWriter();

        // Create a JsonWriter with pretty printing (indentation) configuration
        JsonWriter jsonWriter = Json.createWriterFactory(
                Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true))

        // Write the JSON object with indentation to the StringWriter

        // Close the JsonWriter to release resources

        // Get the formatted JSON string from the StringWriter
        String formattedJson = stringWriter.toString();

        // Print the formatted JSON
        System.out.println("Formatted JSON:");

Json.createWriterFactory() creates a JsonWriterFactory that configures a JsonWriter instance with specific settings.Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true) creates a map with a single entry where the key is JsonGenerator.PRETTY_PRINTING and the value is true. This configuration tells the JSON writer to apply pretty printing (indentation) when writing the JSON.

If you run it, you will see that the output on the Console is a JSON with perfect indentation:

json pretty print in java step-by-step guide

The above code will run with as JBang Script:

jbang JSONPrettyFormat.java

On the other hand, if you want to pretty-print your JSON from inside a Jakarta EE Container (such as WildFly), simply remove the JBang DEPS from the script and include the Jakarta JSON API in your project:


JSON Pretty Print using Google API

Another popular choice for creating JSON from Java is Google’s Gson object. You can use Google’s Gson library to convert Java Objects into their JSON representation and also to convert a JSON string to an equivalent Java object.

Google Gson API has an interesting static method “setPrettyPrinting” which is available in the GsonBuilder class. By using this method, you will be able to have out of the box a JSON formatted text:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(someObject);

Which requires in your pom.xml:



In this tutorial, we’ve explored the significance of JSON pretty printing and how it enhances the readability of JSON data. By employing libraries in Java, such as Gson, or Jakarta EE, developers can format JSON structures for better comprehension and analysis. JSON pretty printing proves invaluable in scenarios involving large or complex JSON datasets, offering a clearer representation of the data’s structure and content. Experiment with different libraries and formatting options to discover the best approach for formatting JSON in your Java applications.