简体   繁体   English

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

[英]Can't access nested dictionaries/arrays from json with swift

I am trying to access ["upper category"]["first category"][0][0] of local json file 我试图访问本地json文件的[“上类别”] [“第一类”] [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"
            ]
        ]
    }
}

with

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

I am not able to access anything beyond the first dictionary. 我无法访问第一本字典以外的任何内容。

I tried several times with options like (I tried multiple older solutions but they don't seem to work for me, maybe swift 3) 我尝试了几次选项(我试过多个较旧的解决方案,但它们似乎对我不起作用,也许很快3)

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

It is likely a noob question, I am new to ios. 这可能是一个noob问题,我是ios的新手。 While any answer extremely appreciated explaining how to write code for other number of nested types would be best 虽然任何答案都非常赞赏,解释如何为其他数量的嵌套类型编写代码是最好的

(xcode 8, swift 3) (xcode 8,swift 3)

It's a bit overkill but you can cast the json to [String:[String:[[String]]]] 这有点矫枉过正,但你可以将json转换为[String:[String:[[String]]]]

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

Otherwise, if for example, the dictionary contains elements other than a nested dictionary, you will just have to cast the top level dictionary to [String:Any] and cast the nested elements individually. 否则,例如,如果字典包含嵌套字典以外的元素,则只需将顶级字典转换为[String:Any]并单独转换嵌套元素。

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

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

    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM