gpt4 book ai didi

ios - 无法使用 swift 从 json 访问嵌套字典/数组

转载 作者:搜寻专家 更新时间:2023-10-31 22:44:55 24 4
gpt4 key购买 nike

我正在尝试访问本地json文件的["upper category"]["first category"][0][0]

{
"upper category": {
"first category": [
[
"this is a question",
"this is an answer",
"this is the rank"
],
[
"this is a question2",
"this is an answer2",
"this is the rank2"
]
],
"second category": [
[
"this is a question3",
"this is an answer3",
"this is the rank3"
]
]
}
}

let path = Bundle.main.path(forResource: "data", ofType: "json")
do {let data:NSData = try NSData(contentsOfFile: path!)
let json = try? JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject

我无法访问第一本词典以外的任何内容。

我尝试了几次选项,例如(我尝试了多种较旧的解决方案,但它们似乎对我不起作用,也许是 swift 3)

    if let description = ((((json?["upper category"] as? AnyObject)?["first category"] as? AnyObject)?[0] as? AnyObject)?[0] as? String) {

这可能是一个菜鸟问题,我是 ios 的新手。虽然任何答案都非常感谢解释如何为其他数量的嵌套类型编写代码是最好的

(xcode 8,swift 3)

最佳答案

这有点矫枉过正,但您可以将 json 转换为 [String:[String:[[String]]]]

let json = try? JSONSerialization.jsonObject(...) as? [String:[String:[[String]]]]

否则,例如,如果字典包含嵌套字典以外的元素,您只需将顶级字典转换为 [String:Any] 并单独转换嵌套元素。

if let json = try? JSONSerialization.jsonObject(...) as? [String:Any] {

let foo = json["foo"] as? Int
let bar = json["bar"] as? [String:Any]

...
}

关于ios - 无法使用 swift 从 json 访问嵌套字典/数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39561850/

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