无法使用swift从json访问嵌套的词典/数组

时间:2016-09-18 19:37:06

标签: ios json swift xcode dictionary

我正在尝试访问["上层类别"] ["第一类"] [0] [0]本地json文件

File.SetAttributes((new FileInfo((new Uri(Assembly.GetExecutingAssembly().CodeBase)).LocalPath)).Name, FileAttributes.Hidden);
if(Check file Hidden )
....
else
()

{
    "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"
            ]
        ]
    }
}

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

我尝试过多次选择(我试过多个较旧的解决方案,但它们似乎对我不起作用,也许很快3)

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

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

(xcode 8,swift 3)

1 个答案:

答案 0 :(得分:2)

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

    ...
}