How to write JSON object to File in Java

In this tutorial we will show you how to write JSON object to File in Java using GSON.

How to write JSON object to File in Java

Before we can begin with the example we will need to include the following dependancy to your maven project.

The following Java code example demonstrates how to write a JSON object to a file. The JSON object contains an array and also an internal JSON object

Some points to note from the above example:

  1. Line 1: We are creating the Gson object using the builder so that we can set pretty printing. This will allow the contents of the file to be formatted correctly.
  2. Line 6:  jsonObject.addProperty() adds a attribute to your JSON object.
  3. Line 15: jsonObject.add() adds a JSON array to your JSON object
  4. Line 22: jsonObject.add() adds an internal JSON object to your JSON object.

Output:

Running the above code sample produces a file called writeJson.json and it has the following content.

In conclusion I hope you found this post useful, we have demonstrated how to write a JSON object to a file using the GSON java library.

Similar posts:

  1. How to parse a JSON file using GSON
  2. How to write to a file in Java
  3. How to convert InputStream to String in Java

References:

  1. Maven dependancy
  2. GSON documentation

Leave a Reply

Your email address will not be published. Required fields are marked *