Java Guide

JSON Formatter for Java

Learn how to format and pretty print JSON in Java using Jackson and Gson — or paste your data into our free online formatter for a one-off job.

Format JSON in Java: Code Examples

Pretty print with Jackson
import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper mapper = new ObjectMapper();

// writerWithDefaultPrettyPrinter() adds indentation
String formatted = mapper
    .writerWithDefaultPrettyPrinter()
    .writeValueAsString(data);

System.out.println(formatted);
Pretty print with Gson
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

Gson gson = new GsonBuilder()
    .setPrettyPrinting()
    .create();

String formatted = gson.toJson(data);
System.out.println(formatted);
Re-format an existing JSON string (Jackson)
ObjectMapper mapper = new ObjectMapper();

Object json = mapper.readValue(rawJsonString, Object.class);
String pretty = mapper
    .writerWithDefaultPrettyPrinter()
    .writeValueAsString(json);

Prefer a quick online tool?

You don't need to write code to format JSON once. Paste it into our free formatter and get clean, indented output instantly — nothing leaves your browser.

Java JSON FAQ

How do I pretty print JSON in Java with Jackson?

Create an ObjectMapper and call writerWithDefaultPrettyPrinter().writeValueAsString(object). Jackson adds standard indentation to the output.

How do I pretty print JSON with Gson?

Build a Gson instance with new GsonBuilder().setPrettyPrinting().create(), then call gson.toJson(object) to get indented output.

Should I use Jackson or Gson?

Both work well. Jackson is the de facto standard in Spring and offers more features; Gson is lightweight and simple. For a one-off format job, an online tool is faster than adding a dependency.

Free JSON Tools You Can Use Right Now

Put these tips into practice with our free online JSON tools. No signup, everything runs in your browser.

Learn More About JSON

JSON Cheat Sheet

All JSON syntax rules and data types on one page.

View cheat sheet
Common JSON Errors

Fix the 10 most frequent JSON syntax mistakes.

Read guide