【问题标题】:Ktor Websocket feature with ContentNeogation feature (JSON / GSON) in ktorKtor Websocket 功能与 ktor 中的 ContentNeogation 功能 (JSON / GSON)
【发布时间】:2021-05-20 10:17:09
【问题描述】:

我正在尝试为 ktor 中的 Websocket 反序列化/序列化 JSON Payload。

目前我正在做类似的事情

// Global property
lateinit var globalGson: Gson

// fun Application.module()
install(ContentNegotiation) {
    gson {
        setDateFormat(DateFormat.LONG)
        setPrettyPrinting()
        globalGson = create() // init global property
    }
}

在处理 websocket 时:

session.incoming.consumeEach { frame ->
            if (frame is Frame.Text)
              globalGson.fromJson(frame.readText(), MyClass::class.java) // use global property
}

是否有推荐的方式将 Websocket 功能与 GSON 功能结合使用?

是否有任何优雅的方法可以访问特定类型的已注册 ContentNeogation 并在没有 ApplicationPipeline 的情况下使用它? (我相信 WebSocketSession 没有)

【问题讨论】:

    标签: json serialization websocket gson ktor


    【解决方案1】:

    不幸的是,无法将ContentNegotiationWebsockets 一起使用来序列化/反序列化帧数据。最好的办法是直接使用gson 库或任何其他此类库。

    【讨论】:

      猜你喜欢
      • 2021-04-26
      • 2021-10-09
      • 1970-01-01
      • 2018-08-01
      • 2020-08-05
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      • 2022-10-07
      相关资源
      最近更新 更多