Skip to content

Gson – Write JSON to a File with Pretty Print

Gson – Write JSON to a File with Pretty Print example shows how to write JSON to a file with pretty printing enabled. By default, Gson prints JSON data in a compact format, but we can easily enable pretty print.

How to save JSON to a file with pretty print?

When we write JSON data to a file, by default, the Gson library writes it in a compact format, that is there are no indentations and spaces. For a large object or list of multiple objects, it becomes very hard to read the file.

Here is the content of the file students.json.

As we can see, the Gson library printed the JSON in a compact format. However, enabling pretty printing is very easy. All we need to do is to use the GsonBuilder to create an object of the Gson class followed by calling setPrettyPrinting method instead of using the Gson constructor.

Here is how to enable pretty print while saving the JSON to a file.

Here is the content of the file students.json after enabling the pretty print.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.