Sobes.tech
Junior

How to work with JSON in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, working with JSON is most often done using third-party libraries. The most popular ones are:

  1. Jackson: Powerful and flexible.
  2. Gson: Easy to use, from Google.
  3. kotlinx.serialization: Native serialization/deserialization for Kotlin.

Example of using kotlinx.serialization:

  1. Adding dependencies in build.gradle.kts:

    // build.gradle.kts
    plugins {
        kotlin("jvm") version "1.9.22"
        kotlin("plugin.serialization") version "1.9.22"
    }
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0")
    }
    
  2. Creating a data class to model the JSON structure:

    // Data class for JSON deserialization
    import kotlinx.serialization.Serializable
    
    @Serializable // Annotation for serialization/deserialization
    data class User(
        val name: String,
        val age: Int
    )
    
  3. Deserializing a JSON string into an object:

    // Deserializing JSON string
    import kotlinx.serialization.json.Json
    
    val jsonString = """{"name":"Alice","age":30}"""
    val user = Json.decodeFromString<User>(jsonString)
    
    // user.name will be "Alice", user.age will be 30
    
  4. Serializing an object into a JSON string:

    // Serializing object into JSON string
    import kotlinx.serialization.json.Json
    
    val userToSerialize = User("Bob", 25)
    val jsonOutput = Json.encodeToString(userToSerialize)
    
    // jsonOutput will be {"name":"Bob","age":25}
    

The choice of library depends on the project requirements for KMP (Kotlin Multiplatform), performance, and ease of use. kotlinx.serialization is the preferred choice for KMP projects due to its native support.

How to work with JSON in Kotlin? — Kotlin - sobes.tech