The JSON pretty print using Gson shows you how to Gson pretty print a json string with GsonBuilder. This is another json pretty print tutorial that we want to introduce with you. And one more tutorial that you can refer, is Pretty print JSON in Java (Jackson)
Other interesting posts you may like
Gson output
By default, Gson will display the JSON output like the below:
1 2 3 4 5 6 7 8 9 10 11 12 |
Student student = new Student(); //set student data student.setName(“David”); student.setAge(“35”); student.setCourses().add("Math"); student.setCourses().add("Foreign Language"); student.setCourses().add("Animal Biology"); Gson gson = new Gson(); String jsonString = gson.toJson(student); System.out.println(jsonString ); |
Here is default output:
1 |
{“name”:”David”,”age”:35,”courses”:[“Math”,”Foreign Language”,”Animal Biology”]} |
Json pretty print in GSON
To enable the Gson pretty print feature, we need to create the Gson object with GsonBuilder.
1 2 3 |
Gson gson = new GsonBuilder().setPrettyPrinting().create(); String jsonString = gson.toJson(student); System.out.println(jsonString ); |
Here is pretty output
1 2 3 4 5 6 7 8 9 |
{ “name”: ”David”, ”age”: 35, ”courses”: [ “Math”, ”Foreign Language”, ”Animal Biology” ] } |
Gson pretty print full example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package com.javabycode.json; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; public class GsonPrettyPrintExample { public static void main(String args[]) { Student student = getStudent(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String jsonString = gson.toJson(student); System.out.println(jsonString); } private static Student getStudent() { Student student = new Student(); student.setName("David"); student.setAge(35); student.setCourses().add("Math"); student.setCourses().add("Foreign Language"); student.setCourses().add("Animal Biology"); return student; } } |
Here is Gson pretty print output
1 2 3 4 5 6 7 8 9 |
{ “name”: ”David”, ”age”: 35, ”courses”: [ “Math”, ”Foreign Language”, ”Animal Biology” ] } |
That’s all on the tutorial JSON pretty print using Gson.