How to pretty-print JSON in Java

Overview

Many times, large JSON objects can be difficult to understand and debug. Hence, pretty-printing JSON objects is necessary. In this shot, we explore how to use different frameworks to pretty-print JSON files.

INDENT_OUTPUT in Jackson

We construct an ObjectMapper object and activate the SerializationFeature.INDENT_OUTPUT feature to generate a well-formatted JSON string. To activate this feature, we must use the ObjectMapper’s enable() method and provide the feature to be enabled.

To use the Jackson library, add the Jackson databind dependency from the Maven Repository.

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class Main{
public static void main(String[] args) throws JsonProcessingException {
String uglyJson = "{\"_id\":\"613215d0899cb431ba05722d\",\"index\":0,\"guid\":\"000f4832-57b3-4489-8b69-1b69d3b74af5\",\"isActive\":false,\"balance\":\"$3,266.13\",\"age\":27,\"eyeColor\":\"blue\",\"name\":\"Franks Hoffman\"}";
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
JsonNode jsonNode = objectMapper.readTree(uglyJson);
String prettyJson = objectMapper.writeValueAsString(jsonNode);
System.out.println(prettyJson);
}
}

The setPrettyPrinting() method in Gson

We add the setPrettyPrinting() method to the GsonBuilder object to enable pretty-printing of JSON while constructing the Gson object.

To use the Gson library, add the Gson dependency from the Maven Repository.

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
public class Main{
public static void main(String[] args) {
String uglyJson = "{\"_id\":\"613215d0899cb431ba05722d\",\"index\":0,\"guid\":\"000f4832-57b3-4489-8b69-1b69d3b74af5\",\"isActive\":false,\"balance\":\"$3,266.13\",\"age\":27,\"eyeColor\":\"blue\",\"name\":\"Franks Hoffman\"}";
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement jsonElement = JsonParser.parseString(uglyJson);
String prettyJson = gson.toJson(jsonElement);
System.out.println(prettyJson);
}
}

Free Resources