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

Abd*_*man 4 kotlin ktor 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()
            }
        }

Run Code Online (Sandbox Code Playgroud)

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

Hor*_*rea 5

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()
            }
        }
Run Code Online (Sandbox Code Playgroud)

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

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