Thread
#serialization
    pajatopmr

    pajatopmr

    1 year ago
    I've been through the serialization guide (very impressive piece of work) but how to deal with custom deserializers for polymorphic classes (cannot use "type" discriminant) has eluded me. Can someone refer me to which section(s) of the guide might contain the information I need?
    v

    Vampire

    1 year ago
    Which is your format?
    pajatopmr

    pajatopmr

    1 year ago
    JSON
    pajatopmr

    pajatopmr

    1 year ago
    Cool, I will check it out. Thanks,
    @Vampire Your suggestion works well with a single level abstraction, something like this:
    object ServerInfoSerializer : JsonContentPolymorphicSerializer<ServerInfo>(ServerInfo::class) {
        override fun selectDeserializer(element: JsonElement) = ServerInfoImpl.serializer()
    }
    
    interface ServerInfo {
        val name: String
        val version: String?
    }
    
    @Serializable
    class ServerInfoImpl(override val name: String, override val version: String?) : ServerInfo
    But how to handle a hierarchy is eluding me at the moment. Something simple like:
    object InitializeResultSerializer : JsonContentPolymorphicSerializer<InitializeResult>(InitializeResult::class) {
        override fun selectDeserializer(element: JsonElement) = when {
            //"serverInfo" in element.jsonObject -> ServerInfoImpl.serializer()
            else -> InitializeResultImpl.serializer()
        }
    }
    
    interface InitializeResult {
        val serverInfo: ServerInfo?
    }
    
    @Serializable
    class InitializeResultImpl(
        override val serverInfo: ServerInfo?
    ) : InitializeResult
    which, when I try to use
    val result: InitializeResult = InitializeResultImpl(serverInfo)
            assertEquals(jsonResult, Json.encodeToString(InitializeResultSerializer, result))
    I get a failure and a message that
    serverInfoImpl
    is not serializable in the scope of
    serverInfo
    which I see clearly. What I don't see is how to satisfy this requirement. Suggestions?