如何使用 kotlinx.serialization 在 Ktor 中序列化 Web Socket Frame.text

How to Serialize Web Socket Frame.text in Ktor with kotlinx.serialization

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() 序列化为 return class 对象 我是 Ktor 世界的新手,我不知道这是否可行

您可以使用您可能已经为 ContentNegotiation 设置的基础 kotlinx.serialization。如果您还没有,可以找到有关如何使 class 可序列化以及如何 encode/decode 到 JSON 格式的说明 here. This will require to make your class (I assumed the name ObjectType) serializable with @Serializable. More details here。我包含了解决方案片段:

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