Course – LS (cat=JSON/Jackson)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Introduction

In this tutorial, we’ll delve into the process of formatting JSON data in Java to enhance its readability.

Often, when dealing with extensive JSON objects, understanding and debugging them can be a daunting task. Consequently, adopting the practice of pretty-printing JSON objects becomes crucial.

To achieve this, we’ll leverage the capabilities of the Jackson and Gson libraries, which provide convenient methods for generating well-formatted JSON output.

2. Pretty Print JSON using Jackson

To pretty-print JSON using Jackson, let’s begin by adding the following dependencies to the pom.xml file:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version>
</dependency>

Always use the latest versions from the Maven central repository for jackson-databind.

2.1. Pretty Print On-Demand

To achieve on-demand pretty printing of JSON, we can utilize the writeWithDefaultPrettyPrinter() method:

String uglyJsonString = "{\"one\":\"AAA\",\"two\":[\"BBB\",\"CCC\"],\"three\":{\"four\":\"DDD\",\"five\":[\"EEE\",\"FFF\"]}}"; 

public String prettyPrintJsonUsingDefaultPrettyPrinter(String uglyJsonString) {
    ObjectMapper objectMapper = new ObjectMapper();
    Object jsonObject = objectMapper.readValue(uglyString, Object.class);
    String prettyJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
    return prettyJson;
}

The result is the well-formatted JSON object:

@Test
public void shouldPrettyPrintJsonStringUsingDefaultPrettyPrinter() throws JsonProcessingException {
    JsonPrettyPrinter jsonPrettyPrinter = new JsonPrettyPrinter();
    String formattedJsonString = jsonPrettyPrinter.prettyPrintJsonUsingDefaultPrettyPrinter(uglyJsonString);
    System.out.println(formattedJsonString);
}
// output:
{
    "one" : "AAA",
    "two" : [ "BBB", "CCC" ],
    "three" : {
        "four" : "DDD",
        "five" : [ "EEE", "FFF" ]
    }
}

2.2. Pretty Print Globally

By enabling the INDENT_OUTPUT setting globally, we can generate a well-formatted JSON string with pretty printing. This ensures that JSON output throughout the system will be consistently formatted in a readable manner.

Let’s proceed to enable the INDENT_OUTPUT setting globally:

public String prettyPrintUsingGlobalSetting(String uglyJsonString) {
    ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
    Object jsonObject = mapper.readValue(uglyJsonString, Object.class);
    String prettyJson = mapper.writeValueAsString(jsonObject);
    return prettyJson;
}

The result is the well-formatted JSON object:

@Test
public void shouldPrettyPrintJsonStringUsingGlobalSetting() throws JsonProcessingException {
    JsonPrettyPrinter jsonPrettyPrinter = new JsonPrettyPrinter();
    String formattedJsonString = jsonPrettyPrinter.prettyPrintUsingGlobalSetting(uglyJsonString);
    System.out.println(formattedJsonString);
}
// output:
{
    "one" : "AAA",
    "two" : [ "BBB", "CCC" ],
    "three" : {
        "four" : "DDD",
        "five" : [ "EEE", "FFF" ]
    }
}

3. Pretty Print JSON using Gson

Let’s first add the Gson Maven dependency:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
</dependency>

Always use the latest versions from the Maven central repository for gson. To pretty-print JSON, we’ll use the setPrettyPrinting() method of GsonBuilder:

public String prettyPrintUsingGson(String uglyJson) {
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    JsonElement jsonElement = JsonParser.parseString(uglyJsonString);
    String prettyJsonString = gson.toJson(jsonElement);
    return prettyJsonString;
}

The result is the well-formatted JSON object:

@Test
public void shouldPrettyPrintJsonStringUsingGson() {
    JsonPrettyPrinter jsonPrettyPrinter = new JsonPrettyPrinter();
    String formattedJsonString = jsonPrettyPrinter.prettyPrintUsingGson(uglyJsonString);
    System.out.println(formattedJsonString);
}
// output:
{
    "one": "AAA",
    "two": [
        "BBB",
        "CCC"
    ],
    "three": {
        "four": "DDD",
        "five": [
            "EEE",
            "FFF"
        ]
    }
}

4. Conclusion

In this article, we have explored various methods for achieving pretty printing of JSON in Java.

The source code accompanying the article can be found over on GitHub.

Course – LS (cat=JSON/Jackson)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – Jackson (eBook) (cat=Jackson)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.