Kotlinx.serialization is a multiplatform serialization library for Kotlin that provides an easy way to convert Kotlin objects to JSON and other formats. Here are the steps to use kotlinx.serialization for JSON serialization and deserialization:
1. Add the kotlinx.serialization dependency to your project. You can do this by adding the following to your Gradle file:
plugins {
id 'org.jetbrains.kotlin.plugin.serialization' version '1.4.31'
}
dependencies {
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.2.1"
}
2. Define your Kotlin class that you want to serialize/deserialize. For example:
import kotlinx.serialization.Serializable
@Serializable
data class Person(val name: String, val age: Int)
3. Serialize a Kotlin object to JSON:
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
val person = Person("John Doe", 30)
val json = Json.encodeToString(person)
println(json) // Output: {"name":"John Doe","age":30}
4. Deserialize JSON to a Kotlin object:
import kotlinx.serialization.decodeFromString
val json = """{"name":"John Doe","age":30}"""
val person = Json.decodeFromString<Person>(json)
println(person) // Output: Person(name=John Doe, age=30)
Additionally, if you have nullable fields in your Kotlin class, kotlinx.serialization provides some annotations to control the serialization of null values.
For example, ‘@Optional‘ can be used to indicate that a field can be null:
import kotlinx.serialization.Optional
@Serializable
data class Person(val name: String, @Optional val age: Int?)
And ‘@SerialName‘ can be used to define a custom name for the serialized field:
import kotlinx.serialization.SerialName
@Serializable
data class Person(@SerialName("fullName") val name: String, val age: Int)
Overall, kotlinx.serialization provides an intuitive and flexible approach to JSON serialization and deserialization in Kotlin.