Pretty-print JSON in Java

How to pretty-print JSON in Java with Jackson, Gson, org.json or Jakarta JSON-P, what formatting changes and what it leaves alone, and when compact output is the better choice.

Pretty-printing JSON in Java means taking a compact JSON string or object and writing it back out with line breaks and indentation so people can read it. The Java SE platform has no built-in JSON API, so in practice this is done with a library such as Jackson, Gson, org.json or an implementation of Jakarta JSON Processing. This review covers what the transformation changes, where it can quietly alter more than whitespace, and when you should keep the compact form.

Is pretty-printing the right choice for your use?

Pretty-printing suits output that people read: debugging sessions, configuration files kept in version control, documentation examples, test fixtures and API responses inspected by hand. The main benefit is that nesting becomes visible at a glance, which makes errors and unexpected values easier to spot. The main tradeoff is that the output is larger and spans several lines, and the exact layout depends on which library and settings you use.

Keep compact JSON when machines are the only readers or when line structure matters:

  • Network payloads, where extra whitespace adds bytes with no benefit to the receiving program.
  • Log pipelines that expect one JSON record per line; multi-line output can split a single event into several broken records.
  • Any data that is signed, hashed or checksummed over its raw bytes, since reformatting changes those bytes even when the parsed data is identical.
  • Systems that compare JSON as plain strings rather than as parsed structures.

A practical pattern is to store and transmit compact JSON and pretty-print only at the point of display, such as in a debug log statement or a developer tool.

What a Java JSON formatter actually changes

This is a formatting transformation, not a character substitution or a visual effect. The formatter parses the input into a structure and serializes it again with insignificant whitespace inserted between tokens. Under the JSON specification (RFC 8259), whitespace between tokens has no meaning, so a correct round trip produces data that parses to the same values. Whitespace inside string values is part of the data and is not altered by indentation.

Because the formatter parses and re-serializes rather than just adding spaces, the output reflects the library's own rules. The points below are where the result can differ from the input in more than layout.

  • Key order: Jackson's tree model keeps object fields in the order they were read. The org.json JSONObject class has historically been backed by an unordered map, so key order in its output may not match the input.
  • Number representation: when Jackson reads into a tree, floating-point values are parsed as double by default, so a value with more digits than a double can hold may be printed differently. Enabling DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS avoids this. Check the equivalent behavior for any other library you use.
  • Character escaping: Gson escapes characters such as <, >, & and = as Unicode escapes by default unless you call disableHtmlEscaping(). The parsed value is the same, but the visible text is not.
  • Duplicate keys: by default Jackson keeps the last value for a repeated key without raising an error, so pretty-printing can silently drop the earlier value. Jackson's strict duplicate detection setting turns this into an error.
  • Line endings and spacing: Jackson's default pretty printer uses the platform line separator and writes a space on both sides of the colon; Gson uses a newline character and no space before the colon. These differences show up in diffs between machines or libraries.

Pretty-printing with Jackson

Jackson is a common choice when a project already uses it for data binding. The example below uses the Jackson 2.x package names; reading into a JsonNode first means you can format any valid JSON without defining a Java class for it.

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper mapper = new ObjectMapper();
JsonNode tree = mapper.readTree(compactJson);
String pretty = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(tree);

To make every write from a mapper indented, enable SerializationFeature.INDENT_OUTPUT on the ObjectMapper instead of using the per-call writer. If you need a different indent string, line separator or colon spacing, configure a DefaultPrettyPrinter and pass it to mapper.writer(printer).

Pretty-printing with Gson

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

Gson gson = new GsonBuilder()
        .setPrettyPrinting()
        .disableHtmlEscaping()
        .create();
JsonElement tree = JsonParser.parseString(compactJson);
String pretty = gson.toJson(tree);

The static JsonParser.parseString method is available in newer Gson releases; older versions used an instance method on JsonParser instead. Leave out disableHtmlEscaping() only if the output will be embedded in HTML and you want the escaping.

Pretty-printing with org.json and Jakarta JSON-P

With org.json, passing an indent width to toString produces indented output. Keep the key-order caveat above in mind.

import org.json.JSONObject;

String pretty = new JSONObject(compactJson).toString(2);

With Jakarta JSON Processing, pass a configuration map containing JsonGenerator.PRETTY_PRINTING set to true when creating a JsonWriterFactory or JsonGeneratorFactory. Indent width and layout are determined by the implementation you choose, so check its documentation if exact formatting matters.

How the same input differs between libraries

Take the compact input {"id":7,"tags":["a","b"],"note":"x < y"}. Based on the documented default printers, Jackson keeps short arrays on one line and spaces the colon on both sides:

{
  "id" : 7,
  "tags" : [ "a", "b" ],
  "note" : "x < y"
}

Gson, configured as in the example above, puts each array element on its own line:

{
  "id": 7,
  "tags": [
    "a",
    "b"
  ],
  "note": "x < y"
}

Without disableHtmlEscaping(), Gson would write the note value as "x \u003c y". All three forms parse to the same data. These outputs illustrate default behavior described in each library's documentation and have not been checked against a specific release here, so confirm them with the version in your build.

Library | Pretty-print call | Default notes
Jackson 2.x | writerWithDefaultPrettyPrinter() or INDENT_OUTPUT | Keeps key order in trees; space around colon; platform line separator
Gson | GsonBuilder.setPrettyPrinting() | HTML-sensitive characters escaped unless disabled; one array element per line
org.json | toString(indentWidth) | Key order may not be preserved
Jakarta JSON-P | PRETTY_PRINTING generator config | Layout depends on the implementation

Will the formatted JSON stay usable after copying or sharing?

Pretty-printed JSON is still valid JSON, so pasting it into another parser, an API client or a config file works as long as the destination accepts multi-line input. Problems tend to come from the destination rather than the JSON: a single-line form field, a command-line argument or a chat tool that reflows text can break the layout, and some destinations convert spaces or quotes. If a value must survive such a destination, share the compact form or wrap the formatted version in a code block where the tool supports one.

For editing and review, consistent indentation is what makes diffs useful. Pick one library and one configuration for files kept under version control, and set the line separator explicitly if team members work on different operating systems.

Accessibility is a gap in the available evidence: no documentation or test results were supplied on how screen readers or other assistive technology handle indented JSON. Indentation conveys nesting visually, and it should not be assumed that this structure is conveyed equally well by every assistive tool. If formatted JSON is shown to end users rather than developers, test with the assistive technology your audience uses, or present the data in a more accessible form such as a labeled table.

Finally, if you format JSON with an online tool rather than in Java code, nothing about a site's appearance tells you whether it stores what you paste. For tokens, credentials or personal data, format locally with one of the libraries above.