Explain Codes LogoExplain Codes Logo

Pretty-print JSON in Java

java
pretty-printing
json
gson
Anton ShumikhinbyAnton Shumikhin·Aug 5, 2024
TLDR

To pretty-print JSON with indentation rapidly in Java, make good use of the Jackson library's ObjectMapper:

import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); String prettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonInput);

Just pass your JSON string jsonInput to the writeValueAsString method and get the formatted output.

Delving into Pretty-printing Libraries

Here, I'll dissect some efficient pretty-printing libraries you can harness for flexible JSON manipulations across Java platforms — highlighted are the Google's Gson, Jackson, and the renowned org.json.

Gson: Your Pretty-printing Friend

Gson promises a user-friendly Java platform where you may swing between Java Objects and their JSON expressions seamlessly. The prime attraction of the Gson library is its direct support for pretty-printing.

// The magical one-liner, makes your JSON pretty like a unicorn 🦄 Gson gson = new GsonBuilder().setPrettyPrinting().create(); String prettyJsonString = gson.toJson(parsedJsonElement); // Ensure 'parsedJsonElement' is a JsonElement object

While using Gson, it's a good practice to parse the JSON first with JsonParser, as a part of the Gson class since JsonParser is now in retirement:

// RIP JsonParser, long live the parseString method! JsonElement parsedJsonElement = JsonParser.parseString(jsonString);

Jackson: The All-In-One Package

Aside from pretty printing, Jackson extends a comprehensive suite of data-binding attributes. Mostly preferred in large-scale projects due to its impeccable efficiency and support.

A gentle reminder for Jackson users: discreetly handle exceptions that might arise from JSON processing:

try { // Jackson smoothly handling the JSON wrestling match ObjectMapper mapper = new ObjectMapper(); String prettyJsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(yourObject); } catch (JsonProcessingException e) { // It's not Jackson, it's you :) e.printStackTrace(); }

Org.json: The Old Reliable

Authored by Douglas Crockford, this library offers a simplistic way to manipulate and represent JSON data in Java. However, its pretty-printing attributes aren't as polished as Gson's:

// Org.json trying hard to look pretty. No worries, you are pretty enough! JSONObject jsonObject = new JSONObject(jsonString); String prettyPrinted = jsonObject.toString(4); // Indent with 4 spaces

A note for org.json users: the JSONObject constructor is deployed to parse the string, while the toString method uses an indent factor for a perfect touch.

Additional Libraries: Gearing up for the JSON Journey

Genson and Moshi

Tackling specialized use-cases? Get your hands on the unique libraries like Genson and Moshi, offering JSON processing with variable syntax and features.

JSON-P: Java EE's Tactic

When dealing with Java EE, opt for a novel approach with javax.json.JsonWriter for pretty-printing:

JsonWriter writer = Json.createWriterFactory(config).createWriter(outputStream); writer.writeObject(jsonObject);

Pretty-printing and Field Order: A Catch

Here's a catch! While dealing with any of these libraries, the field order of your JSON isn't guaranteed to be preserved. It often isn't a showstopper, unless you're presenting the JSON representation as a User Interface or a comparison is to be performed.

Handling Dependencies like a Pro

For a smooth sail with any of the aforementioned libraries, impeccable dependency management is a must. Add dependency snippets to your build.gradle for Gson or Jackson::

// Becoming friends with Gson implementation 'com.google.code.gson:gson:2.8.8' // Handshake with Jackson implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.0'

In the Trenches with Pretty-printing

While you extract the juicy goodness of pretty-printing JSON, draw your considerations to the size of the JSON, its performance impact, and any specific ordering requirements. Pretty-printing larger JSON datasets can be a daunting task due to the increased memory consumption.

Tuning Performance

Never underestimate the art of performance tuning. Pretty-printing could have additional processing overhead. For example, Gson can be mildly slower on larger JSON strings, leading you to a more performant library or a streamlined approach.

Don't Fall into Pitfalls

Stay clear of common mishaps like unwarranted white spaces, escaping characters, or mismatched indents, especially when different systems dealing with JSON are being integrated. So, wear your testing hat and inspect the pretty-printed output thoroughly.