Generate Pretty Print JSON String in Java using Gson

Tags: JSON gson Gson toJson pretty print JSON HashMap to JSON GsonBuilder

In this Java Gson tutorial we learn how to use the Gson library to generate a readable pretty print JSON String from a Java object. Via Java detail Java example we will show you how to use the GsonBuilder.setPrettyPrinting() method to configure Gson to output JSON String that fits in a page for pretty printing.

How to add Gson to the Java project

To use the Gson library in the Gradle build project, add the following dependency into the build.gradle file.

implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.7'

To use the Gson library in the Maven build project, add the following dependency into the pom.xml file.

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

Or you can download the Gson jar file from Maven Central at gson-2.8.7.jar

To have more information about the Gson library you can visit the project repository at github.com/google/gson

How to generate pretty print JSON String in Java

In order to configure Gson to generate a pretty print JSON String we can use the GsonBuilder.setPrettyPrinting() method to instantiate a Gson object. Via the following Java example program we show you how to use the GsonBuilder.setPrettyPrinting() method to initialize a Gson object and then convert a HashMap object into a readable JSON String.

GeneratePrettyPrintJSONExample.java

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.HashMap;
import java.util.Map;

public class GeneratePrettyPrintJSONExample {
    public static void main(String... args) {
        Map<String, Object> data = new HashMap<>();
        data.put("firstName", "Simple");
        data.put("lastName", "Solution");
        data.put("email", "contact@simplesolution.dev");
        data.put("website", "https://simplesolution.dev");
        Map<String, String> address = new HashMap<>();
        address.put("street", "Simple Street");
        address.put("city", "Sample City");
        address.put("country", "Country Name");
        data.put("address", address);

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

        String jsonString = gson.toJson(data);

        System.out.println(jsonString);
    }
}
The output is:
{
  "firstName": "Simple",
  "lastName": "Solution",
  "website": "https://simplesolution.dev",
  "address": {
    "country": "Country Name",
    "city": "Sample City",
    "street": "Simple Street"
  },
  "email": "contact@simplesolution.dev"
}

Happy Coding 😊