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

1. Using PrintWriter

The idea is to create a PrintWriter instance and call its write() function to write the JSON string. To write to a file, construct a FileWriter using the platform’s default character encoding.

The following solution demonstrates this using the JSON for Java library. It creates a file with the JSON string {"offices":["California","Washington","Virginia"],"name":"Microsoft","employees":182268}. The JSON file will be created if the file does not exist, otherwise, the existing file will be truncated.

Download Code

 
We can also use the Gson library to convert an object to a JSON string using its toJson() function, as shown below:

Download Code

2. Using Jackson library

Jackson library already provides the ObjectMapper#writeValue() function to serialize Kotlin objects as a JSON string and write it to a file. A typical invocation for this function would look like below:

Download Code

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