Is it possible to try deserializing String to one ...
# serialization
s
Is it possible to try deserializing String to one of types provided?
FooResponse
is sealed class, I don't control response and therefore cannot add type discriminator as described in https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#sealed-classes At the moment I use this ugly code, is there a better way?
Copy code
val jsonData = jsonSerializer.parseToJsonElement(responseData)

try {
    Json.decodeFromJsonElement<FooResponse.SuccessData>(jsonData)
} catch (e: SerializationException) {
    try {
        Json.decodeFromJsonElement<FooResponse.AnotherCase>(jsonData)
    } catch (e: SerializationException) {
        Json.decodeFromJsonElement<FooResponse.ErrorData>(jsonData)
    }
}
d
You could write your own
KSerializer
, which first deserializes to
JsonElement
, then checks the structure and based on the structure decides which class to decode into.
s
e