The default behaviour when you're printing a JSON String to the console or a file is a compact JSON format. The default behaviour isn't pretty, there will not be any whitespace in the outputed JSON String. Therefore, there will be no whitespace between field names and its value, object fields, and objects within arrays in the JSON output.

NOTE: null values will still be included in collections/arrays of objects). See the Null Object Support tutorial for information on configure Gson to output all null values.




Maven configuration



Java Bean

package org.camelcode;

public class Book {
    private String author;
    private String title;
    private Integer year;
    private Double price;

    public Book(String author, String title, Integer year, Double price) {
        this.author = author;
        this.title = title;
        this.year = year;
        this.price = price;
    }
}


Helper class


You can configure Gson to use Pretty printing with GsonBuilder. Look at the following:
Gson gson = new GsonBuilder().setPrettyPrinting().create(); String jsonOutput = gson.toJson(someObject);


package org.camelcode;

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

public class WriteGson {

    public static void main(String...args) {
        Book book = new Book("camelcode.org", "Gson custom naming", 1989, 49.99);

        Gson gsonCompact = new Gson();
        String jsonCompact = gsonCompact.toJson(book);
        System.out.println(jsonCompact);

        Gson gsonPretty = new GsonBuilder().setPrettyPrinting().create();
        String jsonPretty = gsonPretty.toJson(book);
        System.out.println(jsonPretty);
    }
}


Download


Download source code - Pretty-Printing-JSON-String-With-GSON.zip  2 KB