【问题标题】:How to Serialize Web Socket Frame.text in Ktor with kotlinx.serialization如何使用 kotlinx.serialization 在 Ktor 中序列化 Web Socket Frame.text
【发布时间】:2021-03-09 00:25:47
【问题描述】:
webSocket("/ws") {
            try {
                while (true) {
                    when(val frame = incoming.receive()){
                        is Frame.Text -> {
                            val text = frame.readText() //i want to Serialize it to class object
                            send(Frame.Text(processRequest(text)))
                        }
                        else -> TODO()
                    }
                }
            } finally {
                TODO()
            }
        }

我想序列化frame.readText() 以返回类对象 我对 Ktor 世界完全陌生,我不知道这是否可能

【问题讨论】:

  • 您能否更好地解释一下您的text 变量中有什么?这是一个JSON字符串?或者是其他东西?如果你有一个 JSON 字符串,你可以使用 kotlinx.serialization

标签: kotlin ktor kotlinx.serialization


【解决方案1】:

您可以使用您可能已经为 ContentNegotiation 设置的底层 kotlinx.serialization。如果您还没有,可以在here 找到说明。这将需要使您的课程(我假设名称为ObjectType)可使用@Serializable 序列化。有关如何使类可序列化以及如何编码/解码为 JSON 格式的更多详细信息 here。我包含了解决方案 sn-p:

webSocket("/ws") {
            try {
                while (true) {
                    when(val frame = incoming.receive()){
                        is Frame.Text -> {
                            val text = Json.decodeFromString<ObjectType>(frame.readText())
                            send(Frame.Text(processRequest(text)))
                        }
                        else -> TODO()
                    }
                }
            } finally {
                TODO()
            }
        }

我通常会使用流(需要kotlinx.coroutines

incoming.consumeAsFlow()
        .mapNotNull { it as? Frame.Text }
        .map { it.readText() }
        .map { Json.decodeFromString<ObjectType>(it) }
        .collect { object -> send(processRequest(object))}
//here comes what you would put in the `finally` block, 
//which is executed after flow collection ends

【讨论】:

    猜你喜欢
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 2023-03-28
    • 1970-01-01
    • 2020-05-12
    • 2019-05-02
    • 2021-07-22
    相关资源
    最近更新 更多