New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
JsonDecodingException: Polymorphic serializer was not found for missing class discriminator ('null') #1382
Comments
Deserialization works if I pass classDiscriminator into input json as:
|
Looks like Serialization/Deserialization works only through below steps:
|
If you do not need polymorphism in this place you can deserialize like this |
@shanshin I agree with that. But open polymorphism is the requirement. Is there any way where we can use the discriminator that is already available in Json. We already have a key "type" in core json structure (from Module class). Can you provide a way to use that core json key as discriminator instead of using built-in discriminator or custom classDiscriminator? I tried something like this:
|
I think that |
@sandwwraith Yes I achieved it using |
We can close this issue 👍 |
@iChintanSoni hey, I follow your code and write this @Serializable(with = ItemSerializer::class)
sealed class Item {
abstract val type: String
@Serializable
data class A(val number: Int): Item() {
override val type: String = "A"
}
@Serializable
data class B(val number1: Int, val number2: Int): Item() {
override val type: String = "B"
}
}
object ItemSerializer: JsonContentPolymorphicSerializer<Item>(Item::class) {
override fun selectDeserializer(element: JsonElement): DeserializationStrategy<Item> {
return when (element.jsonObject["type"]?.jsonPrimitive?.content) {
"A" -> Item.A.serializer()
"B" -> Item.B.serializer()
else -> throw Exception("Unknown Item type")
}
}
}
class SealedClassSerializationTest {
@Test
fun testSerialization() {
val formatter = Json {
encodeDefaults = true
prettyPrint = true
}
val item = Item.A(1)
val s = Json.encodeToString(item)
println(s)
val result = Json.decodeFromString<Item>(s)
println(result)
}
} it is very strange, right ? |
@nesteiner Try |
Describe the bug
Unable to deserialize json string. Upon performing decodeFromString() throws Exception:
To Reproduce
I wrote a test case for demonstrate this:
Expected behavior
It should deserialize.
Environment
The text was updated successfully, but these errors were encountered: