使用 kotlin 编写聊天应用程序,历史上来自 nodejs 我有 / 输出格式的 websocket json 对象:
{"action": "join:chatroom", "payload", "chatroom-name"}
{"action": "leave:chatroom", "payload", "chatroom-name"}
{"action": "message", "payload", {"id": 1, "text": "blah", "user": {"name": "Roman"}}}
{"action": "notification", "payload", {"id": 1, "verb": "blah", "user": {"name": "Roman"}}}
尝试采用 kotlinx 序列化以能够在没有运气的情况下使用这种类型的方法似乎sealed class
是我可以尝试的最接近的方法,但如何更改type
为action
采用这种方法 https://ahsensaeed.com/sealed-classes-kotlinx-serialization-deserialization/ 尝试执行以下操作:
@Polymorphic
@Serializable
sealed class BackendAction{
@Serializable
data class Auth(
// val action: String = "authorize",
val payload: String = ""
) : BackendAction()
}
class BackendActionSerializer {
private val sealedModule = SerializersModule {
polymorphic(BackendAction::class) {
BackendAction.Auth::class with BackendAction.Auth.serializer()
}
}
private val serializer: KSerializer<BackendAction>
get() = BackendAction.serializer()
val format: StringFormat
get() = Json(configuration = JsonConfiguration(classDiscriminator = "action"), context = sealedModule)
fun toStringT(json: String): BackendAction {
return format.parse(serializer, json)
}
fun toTString(t: BackendAction): String {
return format.stringify(serializer, t)
}
}
并致电:
val act = BackendAction.Auth("blah")
val serializer = BackendActionSerializer()
val data = serializer.toTString(act)
给了{"action":"com.project.path.BackendAction.Auth","payload":"blah"}
所以我需要映射com.project.path.BackendAction.Auth
到authorize
编辑:
回答我的问题:
@SerialName("authorize")
这很容易:)
@Polymorphic
@Serializable
sealed class BackendAction{
@Serializable
@SerialName("authorize")
data class Auth(
var payload: String = ""
) : BackendAction()
}
此聊天应用程序的工作网络用户界面: https ://www.lonje.com/