【问题标题】:Can't access nested dictionaries/arrays from json with swift无法使用 swift 从 json 访问嵌套字典/数组
【发布时间】:2017-01-26 11:24:03
【问题描述】:

我正在尝试访问本地 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, 快速 3)

【问题讨论】:

    标签: ios json swift xcode dictionary


    【解决方案1】:

    这有点矫枉过正,但您可以将 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]
    
        ...
    }
    

    【讨论】:

    • 如果我的儿子对象不是同质的并且字典中只有一个元素是嵌套字典怎么办?我不能将其转换为 [String: [String: Any]]。而且我无法像 OP 一样获得嵌套字典
    • @rommex 在这种情况下,您将不得不单独转换嵌套元素,我已经更新了我的答案以涵盖这种情况。
    猜你喜欢
    • 2018-12-06
    • 2021-07-18
    • 1970-01-01
    • 2016-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多