I am trying to deserialize a json object that has a recursive hierarchy, however, the json structure does not include type discriminators:
...
"ObjectName": {
"Child1": [
{
"Child2": {
"Field": "Some Field"
}
},
{
"Child2": {
"Field": "Some Field"
}
}
]
}
...
So, I used this custom deserializer when processing the base class, which scans the first key of the jsonobject and inject it as a type discriminator into the json.
(idea of kotlinx serialization — best way to do polymorphic child deserialization)
@Serializable(with = BaseClassDeserializer::class)
@Polymorphic
sealed class BaseClass
@SerialName("Child1")
data class Child1(val pair: Pair<BaseClass, BaseClass>) : BaseClass()
@SerialName("Child2")
data class Child2(val Field: String) : BaseClass()
object BaseClassDeserializer :
JsonTransformingSerializer<BaseClass>(PolymorphicSerializer(BaseClass::class)) {
override fun transformDeserialize(element: JsonElement): JsonElement {
val typeString = element.jsonObject.keys.first()
return JsonObject(element.jsonObject.toMutableMap().also { it["type"] = JsonElement(typeString) })
}
}
However, kotlin complains that it does not know about my class structure of BaseClass.
kotlinx.serialization.json.internal.JsonDecodingException: Serializer for subclass 'And' is not found in the polymorphic scope of 'Conditional'.
Check if class with serial name 'And' exists and serializer is registered in a corresponding SerializersModule.
To be registered automatically, class 'And' has to be '@Serializable', and the base class 'Conditional' has to be sealed and '@Serializable'.
I have to register the hierarchy by myself to stop this error.
private val json = Json {
serializersModule = SerializersModule {
polymorphic(BaseClass::class) {
subclass(Child1::class)
subclass(Child2::class)
}
}
How should I arrange the annotations such that kotlin will help me automatically generate the class hierarchy structure, as I supposed?
mystm is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.