Sling Academy
Home/Kotlin/How to Read and Write JSON Files in Kotlin

How to Read and Write JSON Files in Kotlin

Last updated: November 30, 2024

JSON (JavaScript Object Notation) files are commonly used for transmitting data in a structured way. They are easy to read for humans and parsable for machines. In this article, we'll explore how to read and write JSON files using Kotlin, a modern programming language that you can employ when dealing with JSON files.

Reading JSON Files

To read a JSON file in Kotlin, you would typically use a library such as Jackson or Gson. Both libraries offer excellent support for JSON in Kotlin.

Using Jackson

The following is a step-by-step method for reading a JSON file using the Jackson library:

// Step 1: Add Jackson dependency to your build.gradle file
// implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.13.3")

// Step 2: Create data class matching JSON structure
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import java.io.File

// Define your data class
data class User(val name: String, val age: Int, val email: String)

fun main() {
    val objectMapper = jacksonObjectMapper()
    val user: User = objectMapper.readValue(File("user.json"))
    println(user)
}

Here, you define a data class matching the JSON structure, and use jacksonObjectMapper to read and convert it.

Using Gson

Gson is another popular library that can be used as follows:

// Step 1: Add Gson dependency to your build.gradle file
// implementation("com.google.code.gson:gson:2.9.0")

// Step 2: Create data class matching JSON structure
import com.google.gson.Gson
import java.io.File

// Define your data class
data class User(val name: String, val age: Int, val email: String)

fun main() {
    val gson = Gson()
    val reader = File("user.json").bufferedReader()
    val user: User = gson.fromJson(reader, User::class.java)
    println(user)
}

In this example, you read the JSON content from a file and convert it to an object using Gson.

Writing JSON Files

To write a JSON file, you can again use Jackson or Gson, as both offer straightforward ways to serialize objects to JSON.

Using Jackson

Here's how you can write JSON using the Jackson library:

import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import java.io.File

fun main() {
    val objectMapper = jacksonObjectMapper()
    val user = User(name = "Jane Doe", age = 30, email = "[email protected]")
    objectMapper.writeValue(File("output_user.json"), user)
    println("JSON written successfully")
}

The method writeValue is used to serialize the data class object to JSON, which is then saved to a file.

Using Gson

For Gson, the approach is slightly different but similarly straightforward:

import com.google.gson.Gson
import java.io.File

fun main() {
    val gson = Gson()
    val user = User(name = "Jane Doe", age = 30, email = "[email protected]")
    val json = gson.toJson(user)
    File("output_user.json").writeText(json)
    println("JSON written successfully")
}

Here, you serialize the object to a JSON string and write it to a file using Kotlin's writeText method.

Conclusion

Reading and writing JSON files in Kotlin is painless thanks to powerful libraries like Jackson and Gson. This article covered the basics of reading from and writing to JSON using both libraries, equipping you with the foundation to handle JSON in your Kotlin applications effectively.

Next Article: Processing CSV Files Using Kotlin’s File API

Previous Article: Terminating System Commands Programmatically in Kotlin

Series: Kotlin - File & OS

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin