Skip to main content

How to read and write JSON files in Kotlin

How to read and write JSON files in Kotlin.

Here's a step-by-step tutorial on how to read and write JSON files in Kotlin:

Step 1: Add the JSON dependency

To work with JSON files in Kotlin, you need to add the kotlinx.serialization library to your project. Add the following dependency to your build.gradle file:

implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.0")

Step 2: Define the data class

To represent the structure of the JSON file, you need to define a data class. Each property in the class should match the corresponding JSON field. For example, if your JSON file has a field named "name", you should have a property named "name" in your data class.

import kotlinx.serialization.Serializable

@Serializable
data class Person(
val name: String,
val age: Int,
val email: String
)

Step 3: Read JSON from a file

To read JSON data from a file, you can use the Json.decodeFromString() function provided by the kotlinx.serialization library.

import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import java.io.File

fun main() {
val jsonString = File("data.json").readText()
val person = Json.decodeFromString<Person>(jsonString)
println(person)
}

In the above example, we read the contents of the JSON file into a string using File("data.json").readText(). Then, we use Json.decodeFromString<Person>(jsonString) to deserialize the JSON string into a Person object.

Step 4: Write JSON to a file

To write JSON data to a file, you can use the Json.encodeToString() function provided by the kotlinx.serialization library.

import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.io.File

fun main() {
val person = Person("John Doe", 30, "johndoe@example.com")
val jsonString = Json.encodeToString(person)
File("data.json").writeText(jsonString)
}

In the above example, we create a Person object and then serialize it into a JSON string using Json.encodeToString(person). Finally, we write the JSON string to a file using File("data.json").writeText(jsonString).

That's it! You've learned how to read and write JSON files in Kotlin using the kotlinx.serialization library. Make sure to import the necessary classes and functions, and adjust the file paths and data classes according to your specific requirements.