【发布时间】: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