Pretty printing JSON String with Gson
- Read json file with GSON
- Write json file using GSON
- From Java to JSON
- From JSON to Java
- From JSON to XML
- From XML to JSON
- Exclude fields from JSON using Gson with @Expose
- Pretty printing JSON String with Gson
- Custom JSON field naming with Gson
- Serialize Object with null values using GSON
- Exclude fields from JSON with java modifiers using Gson
- Read json file with GSON
- Write json file using GSON
- Exclude fields from JSON using Gson with @Expose
- Pretty printing JSON String with Gson
- Custom JSON field naming with Gson
- Serialize Object with null values using GSON
- Exclude fields from JSON with java modifiers using Gson
Comments (0)
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);
}
}





Latest Posts
Latest Comments
Tag cloud