Closed
Description
Describe the bug
Exception occurred when trying to deserialize object as sealed root, if it contains field with unknown enum value.
Exception in thread "main" kotlinx.serialization.MissingFieldException: Field 'status' is required for type with serial name 'org.example.Feature', but it was missing at path: $
To Reproduce
@Serializable
internal sealed class TestSealed {
@Serializable
@SerialName("foo")
data class FirstSealed(@SerialName("feature") val feature: Feature) : TestSealed()
}
@Serializable
internal data class Feature(
@SerialName("status") val status: FeatureStatus?,
)
@Serializable
internal enum class FeatureStatus {
@SerialName("first") First,
@SerialName("second") Second,
}
val json = """{
"feature": {
"status": "unknown"
},
"type": "foo"
}"""
fun main() {
val parser = Json {
coerceInputValues = true
explicitNulls = false
ignoreUnknownKeys = true
}
println(parser.decodeFromString<TestSealed>(json))
}
If try to decode as concrete impl, than all is ok parser.decodeFromString<TestSealed.FirstSealed>(json)
Also noticed that moving "type" key up - fixes the problem. Does the order of keys is important?
val json = """{
"type": "foo",
"feature": {
"status": "unknown"
}
}"""
Expected behavior
Decode success, and prints: FirstSealed(feature=Feature(status=null))
Environment
- Kotlin version: [2.1.0]
- Library version: [1.8.0]
- Kotlin platforms: [JVM]
- Gradle version: [8.10]
- IDE version [IntelliJ IDEA 2024.3.1.1 (Community Edition)]
- Other relevant context [MacOS, OpenJDK 23]