How to Read JSON File in Kotlin: Simple Guide
To read a JSON file in Kotlin, you can use libraries like
kotlinx.serialization or Gson. First, read the file content as a string, then parse it into Kotlin objects using the chosen library's deserialization functions.Syntax
Reading a JSON file in Kotlin involves two main steps: reading the file content as a string and then parsing that string into Kotlin objects.
Here is the general syntax using kotlinx.serialization:
File.readText(): Reads the entire file content as a string.Json.decodeFromString<Type>(jsonString): Converts the JSON string into a Kotlin object of the specified type.
kotlin
import kotlinx.serialization.* import kotlinx.serialization.json.* import java.io.File @Serializable data class Person(val name: String, val age: Int) fun readJsonFile(filePath: String): Person { val jsonString = File(filePath).readText() return Json.decodeFromString<Person>(jsonString) }
Example
This example shows how to read a JSON file named person.json containing a person's name and age, then print the parsed object.
kotlin
import kotlinx.serialization.* import kotlinx.serialization.json.* import java.io.File @Serializable data class Person(val name: String, val age: Int) fun main() { // Assume person.json content: {"name":"Alice","age":30} val jsonString = File("person.json").readText() val person = Json.decodeFromString<Person>(jsonString) println("Name: ${person.name}, Age: ${person.age}") }
Output
Name: Alice, Age: 30
Common Pitfalls
- Not marking data classes with
@Serializable: The Kotlin serialization library requires this annotation to work. - File path errors: Make sure the JSON file path is correct and accessible.
- Incorrect JSON format: The JSON must match the Kotlin data class structure exactly.
- Using blocking IO on main thread: For Android or UI apps, avoid reading files on the main thread to prevent freezing.
kotlin
/* Wrong: Missing @Serializable annotation */ data class Person(val name: String, val age: Int) /* Right: Add @Serializable annotation */ @Serializable data class Person(val name: String, val age: Int)
Quick Reference
Summary tips for reading JSON files in Kotlin:
- Use
File.readText()to get JSON as a string. - Use
kotlinx.serializationorGsonto parse JSON. - Annotate data classes with
@Serializablefor kotlinx.serialization. - Ensure JSON structure matches Kotlin classes.
- Handle exceptions for file reading and parsing errors.
Key Takeaways
Use File.readText() to read JSON file content as a string in Kotlin.
Parse JSON strings into Kotlin objects using kotlinx.serialization or Gson libraries.
Always annotate data classes with @Serializable when using kotlinx.serialization.
Ensure the JSON file path and format match your Kotlin data classes.
Handle errors and avoid blocking the main thread when reading files in UI apps.