kotlinx de/serialization 密封 class/enum

kotlinx de/serialization sealed class/enum

使用 kotlin 编写聊天应用程序, 历史上来自 nodejs 我有 websocket json 对象 in/output 格式:

{"action": "join:chatroom", "payload", "chatroom-name"}
{"action": "leave:chatroom", "payload", "chatroom-name"}
{"action": "message", "payload", {"id": 1, "text": "blah", "user": {"name": "Roman"}}}
{"action": "notification", "payload", {"id": 1, "verb": "blah", "user": {"name": "Roman"}}}

尝试采用 kotlinx 序列化以能够使用这种类型的方法,但不幸的是 似乎 sealed class 是我可以尝试的最接近的但如何将 type 更改为 action

采用了这种方法 https://ahsensaeed.com/sealed-classes-kotlinx-serialization-deserialization/ 尝试做类似的事情:

@Polymorphic
@Serializable
sealed class BackendAction{
    @Serializable
    data class Auth(
//        val action: String = "authorize",
        val payload: String = ""
    ) : BackendAction()
}

class BackendActionSerializer {
    private val sealedModule = SerializersModule {
        polymorphic(BackendAction::class) {
            BackendAction.Auth::class with BackendAction.Auth.serializer()
        }
    }

    private val serializer: KSerializer<BackendAction>
        get() = BackendAction.serializer()

    val format: StringFormat
        get() = Json(configuration = JsonConfiguration(classDiscriminator = "action"), context = sealedModule)

    fun toStringT(json: String): BackendAction {
        return format.parse(serializer, json)
    }

    fun toTString(t: BackendAction): String {
        return format.stringify(serializer, t)
    }
}

并调用:

    val act = BackendAction.Auth("blah")
    val serializer = BackendActionSerializer()
    val data = serializer.toTString(act)

给予{"action":"com.project.path.BackendAction.Auth","payload":"blah"} 所以我需要将 com.project.path.BackendAction.Auth 映射到 authorize

编辑:

回答我的问题: @SerialName("authorize") 很简单:)

@Polymorphic
@Serializable
sealed class BackendAction{
    @Serializable
    @SerialName("authorize")
    data class Auth(
        var payload: String = ""
    ) : BackendAction()
}

此聊天应用程序的工作网络 ui 在此处: https://www.lonje.com/

@SerialName("authorize") 表演一下

@Polymorphic
@Serializable
sealed class BackendAction{
    @Serializable
    @SerialName("authorize")
    data class Auth(
        var payload: String = ""
    ) : BackendAction()
}