Sealed class and generic types kotlinx-serialization

Hello, I have a problem regarding kotlinx-serialization. I am writing a library under Sockets (java) Request/Response (classes below) and unfortunately when receiving packets I have to deserialize to SocketRespone even though Any is not serialized. Have you perhaps had a similar problem and have a patent on how to do this?

Class Request/Response

@Serializable
public sealed class SocketResponse<out TYPE> {
    public abstract val id: Uuid

    @Serializable
    public data class Success<out TYPE>(
        public override val id: Uuid,
        public val result: TYPE
    ): SocketResponse<TYPE>()

    @Serializable
    public data class Failure(
        public override val id: Uuid,
        public val message: String
    ): SocketResponse<Nothing>()
}
val line = connection.reader.readLine() ?: return@launch
val request = Json.decodeFromString<SocketRequest<Any>>(line) <---- Error because Any does not have a serializer
1 Like

The class definiton you showed is for SocketResponse but the deserialization tries to deserialize to SocketRequest.

Can you post the definiton of the latter as well?

I guess the actual problem though is, that kotlinx serialization is not able to simply de/serialize Any because it does not use reflection to identify any appropriate type for it.

You either have to use a @Serializable type instead of Any or implement a custom deserializer for Any.

But maybe someone else knows another possibility as well.