kotlinx de /序列化密封类/枚举

时间:2020-06-07 17:44:33

标签: kotlin kotlinx.serialization kotlinx

使用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()
}

此聊天应用程序的工作Web ui此处: https://www.lonje.com/

1 个答案:

答案 0 :(得分:0)

@SerialName("authorize")可以解决问题

@Polymorphic
@Serializable
sealed class BackendAction{
    @Serializable
    @SerialName("authorize")
    data class Auth(
        var payload: String = ""
    ) : BackendAction()
}