Predict the output
The JSON has an extra field "age". What happens?
@Serializable
data class Profile(val name: String, val premium: Boolean = false)
fun main() {
val json = """{"name":"Ana","age":31}"""
val strict = runCatching { Json.decodeFromString<Profile>(json) }
val lenient = Json { ignoreUnknownKeys = true }.decodeFromString<Profile>(json)
println("${strict.isFailure} $lenient")
}Hint 1 of 1
What is the default for ignoreUnknownKeys?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A true Profile(name=Ana, premium=false)
Correct. The default Json rejects unknown keys; the lenient one ignores age and uses the default for premium.
Why not the others?
- B false Profile(name=Ana, premium=false). By default, unknown keys are an error.
- C true Profile(name=Ana, premium=null). premium has a default, so it's false.
- D It doesn't compile. This is valid kotlinx.serialization code.