This post will discuss how to pretty-print a JSON in Java.

1. Using GSON Library

To enable pretty-print with Gson, you can configure the Gson instance to output Json for pretty printing. The idea is to use GsonBuilder to construct a Gson instance and then invoke its setPrettyPrinting() configuration method. This is demonstrated below:

Download Code

Output:

{
  "name": "Google",
  "employees": 140000,
  "offices": [
    "Mountain View",
    "Los Angeles",
    "New York"
  ]
}

 
Alternatively, you can use JsonParser to parse Json into a parse tree of Json elements. The parse() or parseString() method parses the specified JSON string into a parse tree, which then can be passed to the toJson() method.

Download Code

Output:

{
  "name": "Google",
  "employees": 140000,
  "offices": [
    "Mountain View",
    "Los Angeles",
    "New York"
  ]
}

2. Using JSON-Java Library

Alternatively, if you prefer JSON-Java Library, you can use the JSONObject.toString(indentFactor) method to get a pretty-printed JSON representation of the JSONObject. A typical invocation for this method would look like this:

Download Code

Output:

{
    "employees": 140000,
    "name": "Google",
    "offices": [
        "Mountain View",
        "Los Angeles",
        "New York"
    ]
}

3. Using Jackson Library

The Jackson library (com.fasterxml.jackson.databind) also provides the factory method writerWithDefaultPrettyPrinter() to serialize objects with the pretty printer for indentation. Here’s how the code would look like:

Download Code

Output:

{
    "employees": 140000,
    "name": "Google",
    "offices": [
        "Mountain View",
        "Los Angeles",
        "New York"
    ]
}

That’s all about pretty-printing a JSON in Java.