How do I pretty-print JSON string in Google Gson?

In the following example you’ll see how to format JSON string using the Google Gson library. Here are the steps:

  • We create a Map.
  • Put a couple key-value pairs to it. We put a string, a LocalDate object and an array of String[].
  • Create a Gson object using the GsonBuilder. This allows us to configure the Gson object.
  • We use the setPrettyPrinting() to configure Gson to output pretty print.
  • The registerTypeAdapter() allows us to register custom serializer, in this case we use it to serialize LocalDate object.

Here is our code snippet:

package org.kodejava.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

public class GsonPrettyPrint {
    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "Duke");
        map.put("address", "Menlo Park");
        map.put("dateOfBirth", LocalDate.of(2000, Month.FEBRUARY, 1));
        map.put("languages", new String[]{"Java", "Kotlin", "JavaScript"});

        Gson gson = new GsonBuilder()
                .setPrettyPrinting()
                .registerTypeAdapter(LocalDate.class, new LocaleDateAdapter())
                .create();
        String json = gson.toJson(map);
        System.out.println(json);
    }

    static class LocaleDateAdapter implements JsonSerializer<LocalDate> {
        @Override
        public JsonElement serialize(LocalDate date, Type type, JsonSerializationContext jsonSerializationContext) {
            return new JsonPrimitive(date.format(DateTimeFormatter.ISO_DATE));
        }
    }
}

Running this code produces the following result:

{
  "address": "Menlo Park",
  "languages": [
    "Java",
    "Kotlin",
    "JavaScript"
  ],
  "name": "Duke",
  "dateOfBirth": "2000-02-01"
}

Maven Dependencies

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

Maven Central