Explain Codes LogoExplain Codes Logo

Pretty printing JSON from Jackson 2.2's ObjectMapper

java
json-serialization
jackson-library
pretty-printing
Alex KataevbyAlex Kataev·Mar 2, 2025
TLDR

To get a JSON beauty makeover in Jackson, just configure your ObjectMapper like this:

ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); String json = mapper.writeValueAsString(yourObject); // Insert your data object here

Turn on INDENT_OUTPUT to beautify your JSON by adding necessary whitespace. Swap out yourObject with your actual object to be serialized.

Detailed Configuration

String Refactoring

Let's say you have an ugly duckling String containing JSON and you want it to become a beautiful swan. Use the writerWithDefaultPrettyPrinter method:

// "Fairytale transformation in progress..." String prettyJsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonInstance);

Writing to Files

You can write your beautified JSON directly to a file, like keeping a photograph of your object's best look:

// "Your JSON is now runway ready!" mapper.writerWithDefaultPrettyPrinter().writeValue(new File("output.json"), yourObject); // Behold, a JSON star is born!

Gson: The Alternative

If you don't mind trying on a new fashion with Gson, here's how it offers pretty printing:

String json = new GsonBuilder().setPrettyPrinting().create().toJson(yourObject); // JSON on the catwalk!

From File to Fancy

Here's how to read a Plain Jane JSON file and transform it into a prom queen pretty-printed JSON String:

byte[] jsonData = Files.readAllBytes(Paths.get(filePath)); YourClass yourObject = objectMapper.readValue(jsonData, YourClass.class); String prettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(yourObject); // Prom night, here we come!

Deep Dive into ObjectMapper

Playing Safe

While working with ObjectMapper, remember those good manners:

  • Your classes need proper getters and setters.
  • Handle the exceptions that may feel like party crashers.

Set the Tone

You can add your personal touch with custom indentation. More like choosing the music for your JSON party:

DefaultPrettyPrinter printer = new DefaultPrettyPrinter().withIndent(" "); // 4 spaces, the perfect party rhythm! String customPrettyJson = mapper.writer(printer).writeValueAsString(yourObject);

Power of Parsing

ObjectMapper is powerful. It not only writes but reads JSON bravely:

YourClass obj = mapper.readValue(jsonString, YourClass.class); // Like reading a thrilling adventure novel.

It's versatile and can parse from Strings, Files, Streams and more.

Console Output

For that quick photo snap or to showoff your pretty JSON, print it to the console:

System.out.println(prettyJson); // "Look at my JSON, my JSON is amazing!"

Ensure you dance with the right version of Jackson for your pretty printing moves.