JSON
Jackson
ObjectMapper
Pretty Print
Java

Pretty printing JSON from Jackson 2.2's ObjectMapper

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Pretty-printing JSON with Jackson means serializing it with indentation and line breaks so humans can read it comfortably. The standard answer is to use ObjectMapper.writerWithDefaultPrettyPrinter(), and that approach works both when you start from a Java object and when you parse raw JSON into a tree before reformatting it.

Pretty Print a Java Object

If you already have a Java object, the easiest path is to serialize it with the default pretty printer.

java
1import com.fasterxml.jackson.databind.ObjectMapper;
2
3public class PrettyPrintObject {
4    static class User {
5        public String firstName;
6        public String lastName;
7
8        public User(String firstName, String lastName) {
9            this.firstName = firstName;
10            this.lastName = lastName;
11        }
12    }
13
14    public static void main(String[] args) throws Exception {
15        ObjectMapper mapper = new ObjectMapper();
16        User user = new User("Ada", "Lovelace");
17
18        String json = mapper.writerWithDefaultPrettyPrinter()
19                            .writeValueAsString(user);
20
21        System.out.println(json);
22    }
23}

This is the most common use case: take an object and emit readable JSON for logging, debugging, or configuration output.

Pretty Print an Existing JSON String

If the input is already JSON text, parse it first and then write it back with pretty printing.

java
1import com.fasterxml.jackson.databind.JsonNode;
2import com.fasterxml.jackson.databind.ObjectMapper;
3
4public class PrettyPrintString {
5    public static void main(String[] args) throws Exception {
6        String rawJson = "{\"name\":\"Ada\",\"roles\":[\"admin\",\"writer\"]}";
7
8        ObjectMapper mapper = new ObjectMapper();
9        JsonNode tree = mapper.readTree(rawJson);
10
11        String pretty = mapper.writerWithDefaultPrettyPrinter()
12                              .writeValueAsString(tree);
13
14        System.out.println(pretty);
15    }
16}

This is safer than trying to insert line breaks manually because the JSON parser understands the structure correctly.

Why readTree Is Useful

When the source is a raw JSON string, parsing it into a JsonNode first gives you two benefits:

  • invalid JSON fails early with a real parse error
  • the pretty printer formats structural JSON, not arbitrary text

That makes the pipeline more robust than working only with string replacement tricks.

Writing Pretty JSON to a File

Pretty printing is often useful when generating files meant for humans to inspect.

java
1import java.nio.file.Files;
2import java.nio.file.Path;
3import com.fasterxml.jackson.databind.ObjectMapper;
4
5public class WritePrettyJson {
6    public static void main(String[] args) throws Exception {
7        ObjectMapper mapper = new ObjectMapper();
8        String pretty = mapper.writerWithDefaultPrettyPrinter()
9                              .writeValueAsString(new int[] {1, 2, 3});
10
11        Files.writeString(Path.of("output.json"), pretty);
12    }
13}

This is common for local config generation, snapshots, fixtures, or debugging dumps.

Pretty Printing Is for Readability, Not Efficiency

Pretty-printed JSON is larger than compact JSON because it includes whitespace. That is usually fine for logs, config files, or developer-facing diagnostics, but it is often a poor choice for network payloads where size matters.

So the general rule is:

  • pretty print for humans
  • compact print for machines or bandwidth-sensitive paths

Jackson supports both easily, which is why the decision is usually about use case rather than capability.

Custom Pretty Printers Exist

If the default layout is not enough, Jackson also lets you provide a custom pretty printer. Most projects never need this, but it is available when you want stricter formatting control.

In practice, writerWithDefaultPrettyPrinter() is the right first choice unless you have a very specific formatting policy.

Common Pitfalls

The biggest mistake is trying to pretty print JSON by hand with string replacements. That breaks as soon as nested objects, arrays, or escaped characters become involved.

Another issue is assuming pretty printing repairs malformed JSON. It does not. Invalid JSON must still parse successfully before Jackson can reformat it.

Developers also sometimes pretty print large high-throughput API responses unnecessarily, which increases payload size for no operational benefit.

Finally, if you are comparing pretty-printed output in tests, remember that formatting style matters. Test semantic content when possible rather than depending too tightly on exact whitespace layout.

Summary

  • Use writerWithDefaultPrettyPrinter() to pretty print JSON with Jackson.
  • Serialize Java objects directly or parse raw JSON into a JsonNode first.
  • Pretty printing improves readability, not performance.
  • Do not try to format structured JSON with manual string hacks.
  • Reserve pretty output for human-facing uses such as logs, fixtures, and config files.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.