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:
- Jackson: Powerful and flexible.
- Gson: Easy to use, from Google.
- kotlinx.serialization: Native serialization/deserialization for Kotlin.
Example of using kotlinx.serialization:
-
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") } -
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 ) -
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 -
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.