https://kotlinlang.org logo
#serialization
Title
# serialization
i

Invincible

03/29/2023, 3:03 AM
Hi Everybody, I have a Kotlin
RESPONSE<T>
class that is used for handling success and failure cases. The class is defined with a sealed class hierarchy, and I want to serialize it using polymorphism. Here's the code:
Copy code
@Serializable
sealed class RESPONSE<T> {

    @Required
    lateinit var success: Boolean

    @Serializable
    data class SUCCESS<T>(var data: T) : RESPONSE<T>()

    @Serializable
    data class FAILED(var data: ERROR) : RESPONSE<ERROR>()

    class Serializer<T>(private val serializer: KSerializer<T>) : JsonContentPolymorphicSerializer<RESPONSE<*>>(RESPONSE::class) {
        override fun selectDeserializer(element: JsonElement) = when (val success = element.jsonObject["success"]?.jsonPrimitive?.boolean) {
            true -> SUCCESS.serializer(serializer)
            false -> FAILED.serializer()
            else -> throw SerializationException("RESPONSE data structure is invalid")
        }
    }

    companion object {
        @OptIn(InternalSerializationApi::class)
        inline fun <reified T: KSerializer<T>> serializer() = Serializer(T::class.serializer())
    }
}
Could you please advise me on how to serialize this class using polymorphism?
3 Views