gpt4 book ai didi

json - 使用 Kotlinx.serialization 将 JSON 数组解析为 Map

转载 作者:行者123 更新时间:2023-12-03 02:58:42 42 4
gpt4 key购买 nike

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

JSON 是这样的:

[{"someKey": "someValue"}, {"otherKey": "otherValue"}, {"anotherKey": "randomText"}]

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

我无法使用 @SerialName因为 key 不固定。

当我尝试返回Map<String, String>时,我收到此错误:

Can't locate argument-less serializer for class kotlin.collections.Map. For generic classes, such as lists, please provide serializer explicitly.

最后,我想得到 Map<String, String>List<MyObject>我的对象可能在 MyObject(val id: String, val value: String)

有办法做到这一点吗?否则,我正在考虑编写一个字符串读取器来解析我的数据。

最佳答案

您可以像这样实现自己的简单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}") }
}

关于json - 使用 Kotlinx.serialization 将 JSON 数组解析为 Map<String, String>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55675448/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com