【问题标题】:How to use chaining in Kotlin to parse JSON like python如何在 Kotlin 中使用链接来解析 JSON,如 python
【发布时间】:2020-01-08 18:24:51
【问题描述】:

假设我有一个如下的 JSON:

sampleJSON = {

"key1": {
        "nestedkey1": "nestedvalue1",
        "nestedkey2": "nestedvalue2"
},
"key2": {
        "nestedkey3": "nestedvalue3",
        "nestedkey4": "nestedvalue4"
}   
}

现在我想访问 nestedkey2 的值,所以在 python 中(因为它也是 python 字典)我们可以像这样访问,

print(sampleJSON.get("key1").get("nestedkey2"))

但在 kotlin 中,我们必须先显式获取外部 JSON 对象,然后再获取内部值,如下所示:

val outerJO = JSONObject(sampleJSON)
val innerJO = outerJO.getJSONObject("key1")
println(innerJO.get("nestedkey2"))

有没有办法在 Kotlin 中使用类似 python 的链接来访问嵌套的 JSON 对象?有什么图书馆可以做到吗?

【问题讨论】:

  • 为什么不println (JSONObject(sampleJSON).optJSONObject("key1").optString("nestedkey2"))
  • 在运行时获取 json 时,如果 nestedkey2 是 JSONObject(或任何东西)而不是字符串值怎么办?假设它可以是任何东西。

标签: python android json kotlin gson


【解决方案1】:

使用扩展功能很容易实现。以 Gson 库为例:

import com.google.gson.JsonElement
import com.google.gson.JsonParser

fun main() {
    val jsonString = """
        {

"key1": {
        "nestedkey1": "nestedvalue1",
        "nestedkey2": "nestedvalue2"
},
"key2": {
        "nestedkey3": "nestedvalue3",
        "nestedkey4": "nestedvalue4"
}   
}
    """
    val json = JsonParser().parse(jsonString)
    val result = json["key1"]["nestedkey2"] // Even shorter that in Python

    println(result)
}

private operator fun JsonElement.get(key: String) = this.asJsonObject.get(key)

【讨论】:

  • 来吧伙计,您将 JsonElement 指定为仅作为 JsonObject。它不适用于 Array 情况。
猜你喜欢
  • 2022-01-03
  • 2016-02-12
  • 2018-07-23
  • 2017-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-01
相关资源
最近更新 更多