Meika
06/14/2023, 7:21 PMkotlinx.serialization.json.internal.JsonDecodingException: Polymorphic serializer was not found for missing class discriminator ('null')
when trying to decode json to data class with a generic. code in thread 🧵Meika
06/14/2023, 7:21 PMinterface Attribute
@Serializable
data class NameAttribute(val name: String) : Attribute
@Serializable
data class StuffAttribute(val stuff: Int) : Attribute
@Serializable
data class SomeData<A : Attribute>(
val id: String,
val type: String,
val attribute: A
)
test:
private val json = Json {
ignoreUnknownKeys = true
isLenient = true
serializersModule = SerializersModule {
polymorphic(Attribute::class) {
subclass(NameAttribute::class)
subclass(StuffAttribute::class)
}
}
}
@Test
fun testAttributeDeserialize() {
val response = """
{
"id": "some id",
"type": "name",
"attribute": {
"name": "name here"
}
}
""".trimIndent()
val result = json.decodeFromString<SomeData<Attribute>>(response)
assertEquals("some id", result.id)
assertEquals("name here", (result.attribute as NameAttribute).name)
val stuffResponse = """
{
"id": "stuff id",
"type": "stuff",
"attribute": {
"stuff": 1
}
}
""".trimIndent()
val stuffResult = json.decodeFromString<SomeData<Attribute>>(stuffResponse)
assertEquals("stuff id", stuffResult.id)
assertEquals(1, (stuffResult.attribute as StuffAttribute).stuff)
}
am I missing something obvious here?asdf asdf
06/14/2023, 9:51 PMtype
)
Json for the SomeData
with a StuffAttribute
should look like this:
{
"id": "stuff id",
"type": "stuff",
"attribute": {
"type": "<package>.StuffAttribute",
"stuff": 1
}
}
asdf asdf
06/14/2023, 9:52 PM@SerialName("name" / "stuff")
to the respective classes to avoid writing out the fully qualified nameasdf asdf
06/14/2023, 10:01 PMSomeData
is just a generic Attribute
You can just change:
val stuffResult = json.decodeFromString<SomeData<Attribute>>(stuffResponse)
to
val stuffResult = json.decodeFromString<SomeData<StuffAttribute>>(stuffResponse)