Developer Documentation
Java
Updated September 19, 2026

Format JSON in Java

Pretty-print JSON with predictable indentation and validation in Java.

Formatting JSON means parsing valid JSON and serializing it again with whitespace and indentation that make the structure easier to read. Parsing first also catches malformed input.

Quick Start#

The following example uses the standard Java API or a widely used package for this task.

Quick start with Jackson#

Java
1// Maven: com.fasterxml.jackson.core:jackson-databind2import com.fasterxml.jackson.databind.JsonNode;3import com.fasterxml.jackson.databind.ObjectMapper;45ObjectMapper mapper = new ObjectMapper();6JsonNode value = mapper.readTree(input);7String formatted = mapper.writerWithDefaultPrettyPrinter()8    .writeValueAsString(value);9System.out.println(formatted);

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

Write a file#

Java
1JsonNode value = mapper.readTree(Files.readString(Path.of("input.json")));2String formatted = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(value);3Files.writeString(Path.of("formatted.json"), formatted + System.lineSeparator());

Important Notes#

Use a tree model (JsonNode) when formatting arbitrary JSON instead of binding it to an application DTO.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement JSON Formatter in other languages: