Skip to content

Gson – Write JSON to a file

Gson – Write JSON to a file example shows how to write JSON data to a file using the Gson library in Java. This example also shows how to use the toJson method to save JSON to a file.

How to write JSON data to a file?

Gson library provides various ways to save JSON data to a file. The most common method is to use the toJson method of the Gson class. We can utilize the toJson method that accepts a writer object along with the JSON that we want to write to a file.

This toJson method serializes the given object in JSON representation and writes to the specified writer.

Here is a quick example of that.

Here is the file content after running the program.

Instead of writing individual employee objects, we can also write a list of employees as given below.

In this case, the Gson automatically converts a List object to a JSON array and writes all employee objects as its elements. Here is the file content after running the program.

Important Note: I have used try with resources to open a writer that closes the writer automatically. But if you are not using that and not seeing the JSON output in the file, make sure to flush and close the writer object.

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

About the author

Leave a Reply

Your email address will not be published.