With kotlinx.serialization, annotate the class with @Serializable and call Json.encodeToString(value). Gson and Moshi are alternatives that work through reflection.
// build.gradle.kts
plugins {
kotlin("plugin.serialization") version "2.0.0"
}
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.0")
}import kotlinx.serialization.*
import kotlinx.serialization.json.Json
@Serializable
data class User(val name: String, val age: Int, val email: String? = null)
val json = Json { prettyPrint = true; encodeDefaults = false }
val text = json.encodeToString(User("Ada", 36)) // {"name":"Ada","age":36}
val user = json.decodeFromString<User>(text) // back to an object- Gson:
Gson().toJson(user)needs no plugin but ignores Kotlin null safety and default values. - Moshi: add the Kotlin codegen or reflection adapter, then
moshi.adapter(User::class.java).toJson(user). - kotlinx.serialization generates code at compile time, so it works on Kotlin Multiplatform and with R8 shrinking more predictably.
