Interface polymorphic deserialization with nested subclasses
See original GitHub issueDescribe the bug Can´t deserialize a JSON using polymorphic deserialization and interfaces, if the structure coin nested implementation of the interface.
To Reproduce Given the following class hierarchies:
interface Deliverable
@Serializable
@SerialName("box")
data class Box(val address: String) : Deliverable
@Serializable
@SerialName("parcel")
data class Parcel(val senderNumber: Int, val box: Box) : Deliverable
And the corresponding SerializersModule
to register the implementations:
private val module = SerializersModule {
polymorphic(Deliverable::class) {
subclass(Box::class)
subclass(Parcel::class)
}
}
Whenever I try to deserialize a matching JSON string. i.e :
@Test
fun `deserialize parcel`() {
val deliverable = """
{
"type":"parcel",
"senderNumber": "5",
"box": {
"type": "box",
"address": "new york"
}
}
""".trimIndent()
val box = Box("new york")
val parcel = Parcel(5, box)
val result = Json { serializersModule = module}.decodeFromString<Deliverable>(deliverable)
Truth.assertThat(result).isEqualTo(parcel)
}
I get the following error:
kotlinx.serialization.json.internal.JsonDecodingException: Encountered unknown key 'type'. Use 'ignoreUnknownKeys = true' in 'Json {}' builder to ignore unknown keys
My assumption is that since Parcel
has an explicit implementation declared rather than a Deliverable
then the polymorphic strategy for interfaces its not applied and cant account for the type field?.
But if that’s the case how’s the correct way of handling these situations?
Disclaimer:
Adding 'ignoreUnknownKeys = true'
like the error suggest fixes the issues but it doesn’t feel right to enable this for this use case, or maybe I´m missing a key part here
Environment
- Kotlin version: [1.4.10]
- Library version: [1.0.1]
- Kotlin platforms: [JVM]
- Gradle version: [6.5]
- IDE version [Android Studio 4.1]
Issue Analytics
- State:
- Created 3 years ago
- Comments:10 (5 by maintainers)
Top GitHub Comments
Can this be closed now?
Can confirm I’m having the same problem.
kotlin_version=1.4.10 kotlinx_serialization_version=1.0.1