使用 Kotlinx.serialization 将 JSON 数组解析为 Map<String, String>

Rul*_*jía 6 json kotlin kotlin-multiplatform kotlinx.serialization

我正在编写一个 Kotlin 多平台项目(JVM/JS),我正在尝试使用 Kotlinx.serialization 将 HTTP Json 数组响应解析为 Map

JSON 是这样的:

[{"someKey": "someValue"}, {"otherKey": "otherValue"}, {"anotherKey": "randomText"}]
Run Code Online (Sandbox Code Playgroud)

到目前为止,我能够将 JSON 作为字符串获取,但是我找不到任何文档来帮助我构建 Map 或其他类型的对象。所有这些都说明了如何序列化静态对象。

我无法使用,@SerialName因为密钥未固定。

当我尝试返回 a 时Map<String, String>,出现此错误:

Can't locate argument-less serializer for class kotlin.collections.Map. For generic classes, such as lists, please provide serializer explicitly.
Run Code Online (Sandbox Code Playgroud)

最后,我想得到一个Map<String, String>或一个List<MyObject>我的对象可以在哪里MyObject(val id: String, val value: String)

有没有办法做到这一点?否则,我只想编写一个字符串阅读器来解析我的数据。

Ale*_*ger 9

你可以DeserializationStrategy像这样实现你自己的简单:

object JsonArrayToStringMapDeserializer : DeserializationStrategy<Map<String, String>> {

    override val descriptor = SerialClassDescImpl("JsonMap")

    override fun deserialize(decoder: Decoder): Map<String, String> {

        val input = decoder as? JsonInput ?: throw SerializationException("Expected Json Input")
        val array = input.decodeJson() as? JsonArray ?: throw SerializationException("Expected JsonArray")

        return array.map {
            it as JsonObject
            val firstKey = it.keys.first()
            firstKey to it[firstKey]!!.content
        }.toMap()


    }

    override fun patch(decoder: Decoder, old: Map<String, String>): Map<String, String> =
        throw UpdateNotSupportedException("Update not supported")

}


fun main() {
    val map = Json.parse(JsonArrayToStringMapDeserializer, data)
    map.forEach { println("${it.key} - ${it.value}") }
}
Run Code Online (Sandbox Code Playgroud)