如何使用SwiftyJSON在Swift中使用`for - in`迭代JSON数据?

时间:2015-12-28 17:05:28

标签: json swift swifty-json

我是Swift,JSON和SwiftyJSON的新手。试图读取json数据并输出它只是为了学习。下面的代码完美无缺。但是,我认为可以使用for (key, json) in jsonData来完成;但是,我不能这样做。有什么指针吗?

func loadLocationData() {

    if let path = NSBundle.mainBundle().pathForResource("cityList", ofType: "json") {
        do {
            let data = try NSData(contentsOfURL: NSURL(fileURLWithPath: path), options: NSDataReadingOptions.DataReadingMappedIfSafe)
            let json = JSON(data: data)
            if json != JSON.null {

                if let cityArray = json["country"]["city"].array {

                    for city in cityArray {
                        DLog("\(city["Name"])")

                        if let districtArray = city["district"].array {

                            for district in districtArray {
                                DLog("-- \(district["Name"])")

                                if let placeArray = district["place"].array {

                                    for place in placeArray {

                                        DLog("  --  \(place["Name"])")
                                    }
                                }
                            }
                        }
                    }
                }

            } else {
                print("could not get json from file, make sure that file contains valid json.")
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    } else {
        print("Invalid filename/path.")
    }
}

0 个答案:

没有答案