我正在开发一个 kotlin 包装器来开发不和谐应用程序,并且我正在使用 ktor 客户端来处理它。
我遇到了序列化问题。
为了处理不和谐的 websocket 框架,我创建了一个包含此 json 的类
GatewayIntent
{
"op": 0,
"d": {},
"s": 42,
"t": "GATEWAY_EVENT_NAME"
}
在此模型中,我使用 op
作为 classDicriminator,并且我有与我必须处理的每个事件相对应的子类,并且
d
字段是不同的类。在 ktor websocket 会话中,我创建多态配置
install(WebSockets) {
contentConverter = KotlinxWebsocketSerializationConverter(Json {
ignoreUnknownKeys = true
encodeDefaults = true
serializersModule = SerializersModule {
polymorphic(GatewayIntent::class) {
subclass(HelloIntent::class)
subclass(HBackIntent::class)
subclass(IdentifyIntent::class)
}
}
classDiscriminator = "op"
})
}
反序列化事件效果很好,但是当我尝试序列化时,用作 classDiscriminator 的 op
字段未设置到 json 字符串中。
sendSerialized(HelloIntent(), typeInfo<GatewayIntent>())
或手动 json 转字符串。
send(Json.encodeToString(GatewayIntent.serializer(), HelloIntent()))