Java Gson pretty printing



Gson is a Java serialization/deserialization library to convert Java Objects into JSON and back. Gson was created by Google for internal use and later open-sourced.

Check out top GSON tutorial at Google GSON Tutorial.

Java Gson Maven dependency

This is a Maven dependency for Gson:
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
</dependency>

Java Gson pretty printing example

Gson has two output modes: compact and pretty. The example pretty prints the JSON output.
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.HashMap;
import java.util.Map;

public class GsonPrettyPrinting {

    public static void main(String[] args) {

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        
        Map<String, Integer> items = new HashMap<>();
        
        items.put("chair", 3);
        items.put("pencil", 1);
        items.put("book", 5);

        gson.toJson(items, System.out);
    }
}
Output:
{
  "chair": 3,
  "book": 5,
  "pencil": 1
}
The setPrettyPrinting() method sets the pretty-printing mode:
Gson gson = new GsonBuilder().setPrettyPrinting().create();

Comments