How To Pretty Print JSON In Java

Table of Contents

Introduction

Here I am going to show you how to pretty print JSON in Java. I am going to use here JSON, Jackson and Google Gson libraries to prettify the JSON data. I am also going to show you how to read and write JSON file using Java 8 or later version. I am going to show you how to prettify JSON string as well as JSON file data.

Why do you need to prettify the JSON data?

Because you want to read the JSON data manually when you receive the JSON data as a response of a, for example, REST service. You want to find out the issue with JSON data which might have been passed as an input to a REST service. So an ugly one liner JSON data might be very difficult to read and keep a track of a particular key/value pair with a naked eye. Sometimes you might need to share your JSON data to someone else when you are requested to do so.

Related Post:

Prerequisites

Java at least 8, Jackson 2.11.2, Gson 2.8.6, JSON 20200518

Pretty Print JSON

I am going to use a sample JSON data to be used to pretty print for this example. I am going to use JSON, Jackson and Gson libraries to pretty print. I am also going to show you how to prettify the JSON string as well as JSON file data.

Using Jackson Library

As a first step you need to add two dependencies either your pom.xml file or build.gradle script depending on your build tool.

If you are using gradle as a build tool then you can use below dependencies:

implementation('com.fasterxml.jackson.core:jackson-core:2.11.2')
implementation('com.fasterxml.jackson.core:jackson-databind:2.11.2')

If you are using maven as a build tool then you can use below dependencies format:

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

The whole source code you can download later from the Source Code section.

The first example I am showing here how to prettify the JSON string using Jackson:

ObjectMapper mapper = new ObjectMapper();

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

        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(mapper.readTree(inputJson)));

The above code snippets will give you the following output:

{
  "one" : "AAA",
  "two" : [ "BBB", "CCC" ],
  "three" : {
    "four" : "DDD",
    "five" : [ "EEE", "FFF" ]
  }
}

The same thing can be achieved while you are reading from a JSON file and want to write output to a JSON file.

ObjectMapper mapper = new ObjectMapper();

Path path = Paths.get("input.json");

String str = new String(Files.readAllBytes(path));

Files.write(Paths.get("output.json"),
		mapper.writerWithDefaultPrettyPrinter().writeValueAsBytes(mapper.readTree(str)));

It is assumed that your input.json file has the ugly or one liner JSON data and you will receive the same output with pretty print in the output.json file. The input and output JSON files are placed in the root directory of the project.

You can also set the indent feature in the ObjectMapper instance instead of calling the method writerWithDefaultPrettyPrinter() in the mapper instance. In this case your ObjectMapper instance should look like the following:

ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);

And your final write method should look something similar to the below:

System.out.println(mapper.writeValueAsString(mapper.readTree(inputJson)));

Or

Files.write(Paths.get("output.json"), mapper.writeValueAsBytes(mapper.readTree(str)));

Using Google Gson Library

You need to add only one dependency for Gson API.

For gradle based project:

implementation('com.google.code.gson:gson:2.8.6')

For maven based project:

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

The first thing is you need to create a Gson instance with pretty print feature.

Gson gson = new GsonBuilder().setPrettyPrinting().create();

For string based JSON data you can use the following code snippets:

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

        System.out.println(gson.toJson(JsonParser.parseString(inputJson)));

For file based JSON data you can use the following code snippets:

Path path = Paths.get("input.json");

String str = new String(Files.readAllBytes(path));

Files.write(Paths.get("output.json"), gson.toJson(JsonParser.parseString(str)).getBytes());

Gson API will also prettify your JSON but in a little different way than Jackson API.

{
  "one": "AAA",
  "two": [
    "BBB",
    "CCC"
  ],
  "three": {
    "four": "DDD",
    "five": [
      "EEE",
      "FFF"
    ]
  }
}

Using JSON Library

You can also do the same thing using JSON library. You just need to pass the JSON data while you are creating JSONObject and later just use the indent factor to pretty print your JSON.

Use the following dependency in your pom.xml or build.gradle script.

<dependency>
	<groupId>org.json</groupId>
	<artifactId>json</artifactId>
	<version>20200518</version>
</dependency>

Or

implementation('org.json:json:20200518')

The following code snippets prettify JSON string as well JSON file data.

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

System.out.println(new JSONObject(inputJson).toString(4));

Path path = Paths.get("input.json");

String str = new String(Files.readAllBytes(path));

Files.write(Paths.get("output.json"), new JSONObject(str).toString(4).getBytes());

The above code gives the following output.

{
    "one": "AAA",
    "two": [
        "BBB",
        "CCC"
    ],
    "three": {
        "four": "DDD",
        "five": [
            "EEE",
            "FFF"
        ]
    }
}

That’s all about how to pretty print your JSON data. There might be other libraries available and you can search in the Google.

Source Code

Download

Leave a Reply

Your email address will not be published. Required fields are marked *