Write JSON to a file in Kotlin
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import org.json.JSONException import org.json.JSONObject import java.io.FileWriter import java.io.PrintWriter import java.nio.charset.Charset fun main() { val path = "/json/microsoft.json" val json = JSONObject() try { json.put("name", "Microsoft") json.put("employees", 182268) json.put("offices", listOf("California", "Washington", "Virginia")) } catch (e: JSONException) { e.printStackTrace() } try { PrintWriter(FileWriter(path, Charset.defaultCharset())) .use { it.write(json.toString()) } } catch (e: Exception) { e.printStackTrace() } } |
We can also use the Gson library to convert an object to a JSON string using its toJson() function, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import com.google.gson.Gson import java.io.FileWriter import java.io.PrintWriter class Company( var name: String, var employees: Int, var offices: List<String> ) fun main() { val companies = Company( "Microsoft", 182268, listOf("California", "Washington", "Virginia") ) val path = "/json/microsoft.json" try { PrintWriter(FileWriter(path)).use { val gson = Gson() val jsonString = gson.toJson(companies) it.write(jsonString) } } catch (e: Exception) { e.printStackTrace() } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import org.codehaus.jackson.map.ObjectMapper import java.io.File import java.io.IOException class Company( var name: String, var employees: Int, var offices: List<String> ) fun main() { val companies = Company( "Microsoft", 182268, listOf("California", "Washington", "Virginia") ) val path = "/json/microsoft.json" try { val mapper = ObjectMapper() mapper.writeValue(File(path), companies) } catch (e: IOException) { e.printStackTrace() } } |
That’s all about writing JSON data to a file in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)