This post will discuss how to write JSON data to a file in Java.

1. Using PrintWriter

A simple solution is to create a new PrintWriter instance from the character-output stream and use its write() method to write the JSON string to a file. You can construct and pass a FileWriter given a file name, using the specified charset or the platform’s default one. Note that if the file does not exist, a new file will be created; otherwise, the existing file will be truncated.

The following solution uses JSON-Java library to create companies.json file, at the specified location, with the JSON content {"offices":["Mountain View","Los Angeles","New York"],"name":"Google","employees":140000}.

Download Code

 
Here’s an alternative solution that uses the Gson Java library to convert an object to its JSON representation. Gson provides the toJson() method to convert a Java object to a JSON string and write it to a file using PrintWriter.

Download Code

2. Using Jackson library

Jackson is a high-performance library for processing JSON data in Java. It provides an ObjectMapper class for reading and writing JSON. The idea is to use the writeValue() method to serialize Java objects as JSON String and write the JSON to the supplied file. The following program demonstrates it:

Download Code

That’s all about writing JSON data to a file in Java.