1
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 世界完全陌生,我不知道这是否可能

4

1 回答 1

1

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

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
于 2020-11-26T08:00:11.433 回答