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 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()
                .registerTypeAdapter(LocalDate.class, new LocaleDateAdapter())
        String json = gson.toJson(map);

    static class LocaleDateAdapter implements JsonSerializer<LocalDate> {
        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": [
  "name": "Duke",
  "dateOfBirth": "2000-02-01"

Maven Dependencies

<!-- -->

Maven Central

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.