繁体   English   中英

Swift中的多维数组/字典循环

[英]Multidimensional array/dictionary loop in Swift

我正在尝试遍历我从JSON字符串中获得的多维数组/字典。 最初我来自PHP,所以我的方法可能有点偏离。

我的问题是我似乎无法进入子数组/字典。

到目前为止,我的代码:

func getJSON(){
    let url = NSURL(string: url)
    URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
        if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
            print(jsonObj!)
            let array = jsonObj!.allKeys

            for keys in array {
                print(keys)
            }

            OperationQueue.main.addOperation({
                //Nothing to do right now
            })
        }
    }).resume()
}

我的JSON:

{
    "ArrayName1": {
        "info": "This is my first array!",
        "more": "Even more info!"
    },
    "ArrayName2": {
        "info": "This is my second array!",
        "more": "Even more info about the second array!"
    }
}

该函数会打印出很好的键(例如ArrayName1),但是如何深入数组呢? 要打印“信息”?

如果您确定它是[String:[String:Any]]形式的字典,则可能需要尝试一下。

if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: [String: Any]] {
    let array = jsonObj!.allKeys

     for key in array {
            print(key)
            let info = jsonObj[key]["info"] as! String
     }

}
  • 首先,不要在Swift 3中使用NSURL 。有一个本机结构URL
  • 第二, .allowFragments毫无用处,因为JSON显然是集合类型。
  • 第三,不要在Swift中使用NSDictionary ,而要使用本机类型Dictionary
  • 第四,错误处理至少处理数据任务传递的可能错误。

所有集合类型都是字典。 使用快速枚举来解析键和值。 所有键和值都是字符串。

func getJSON(){
    let url = URL(string: url)!
    URLSession.shared.dataTask(with: url, completionHandler: {(data, response, error) -> Void in
        if error != nil {
           print(error!)
           return
        }
        do {
           if let jsonObj = try JSONSerialization.jsonObject(with: data!) as? [String:[String:String]] {               
               for (key, innerDictionary) in jsonObj {
                    print(key)
                    if let info = innerDictionary["info"] {
                        print("info", info)
                    }
               }
               DispatchQueue.main.async {
                   //Nothing to do right now
               }
           } else { print("The JSON object is not [String:[String:String]]") }
        } catch {
           print(error)
        }
    }).resume()
}

暂无
暂无

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

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