JSON with kotlinx.serialization and Moshi
Setup
kotlin
// plugins
alias(libs.plugins.kotlin.serialization)
// dependencies
implementation(libs.kotlinx.serialization.json)
Decode
kotlin
@Serializable
data class Author(val name: String, val country: String)
@Serializable
data class Course(
val id: Int,
val title: String,
@SerialName("is_free") val isFree: Boolean = false, // different JSON name, default value
val price: Double = 0.0,
val tags: List<String> = emptyList(),
val author: Author,
val subtitle: String? = null // may be missing or null
)
val json = Json {
ignoreUnknownKeys = true // ignore fields you did not declare
coerceInputValues = true // use defaults for nulls in non-null fields
prettyPrint = true
}
val text = """{"id":7,"title":"Kotlin Basics","is_free":true,"tags":["kotlin","android"],
"author":{"name":"Asha","country":"India"},"extra":"ignored"}"""
val course = json.decodeFromString<Course>(text)
println(course.author.name) // Asha
val back = json.encodeToString(course) // object -> JSON text
Make fields optional with defaults: APIs change. If a field can be missing, give it a default value or make it nullable. Otherwise decoding throws an exception.
Lists and Wrappers
kotlin
@Serializable
data class Page<T>(val results: List<T>, val total: Int)
val page = json.decodeFromString<Page<Course>>(responseText)
val courses = json.decodeFromString<List<Course>>(listText)
Enums
kotlin
@Serializable
enum class Level {
@SerialName("beginner") BEGINNER,
@SerialName("advanced") ADVANCED
}
Handle Parsing Errors
kotlin
val result = runCatching { json.decodeFromString<Course>(text) }
result.onSuccess { println(it.title) }
.onFailure { println("Bad JSON: ${it.message}") }
Separate API Models from App Models
kotlin
@Serializable data class CourseDto(val id: Int, val title: String, @SerialName("is_free") val isFree: Boolean = false)
data class CourseUi(val id: Int, val title: String, val badge: String)
fun CourseDto.toUi() = CourseUi(id, title, if (isFree) "FREE" else "PAID")
Moshi (Alternative)
kotlin
@JsonClass(generateAdapter = true)
data class User(val name: String, @Json(name = "e_mail") val email: String?)
val moshi = Moshi.Builder().build()
val adapter = moshi.adapter(User::class.java)
val user = adapter.fromJson("""{"name":"Asha","e_mail":"a@b.com"}""")
Choice: kotlinx.serialization is the Kotlin-first choice and works with Compose navigation routes too. Moshi is also fine and common in existing code.
Conclusion
Mark classes @Serializable, set ignoreUnknownKeys, give optional fields defaults and convert API models to app models.
Quick Summary: Use @Serializable, @SerialName, defaults and nullable fields, Json { ignoreUnknownKeys = true } and decodeFromString.

