如何在没有密钥的情况下解析JSON文件?

时间:2017-04-21 14:23:25

标签: json swift

我已从此网址下载JSON文件:https://raw.githubusercontent.com/David-Haim/CountriesToCitiesJSON/master/countriesToCities.json

我将所有JSON文件解析为let json

后,我陷入困境
 let requestURL: NSURL = NSURL(string: "https://raw.githubusercontent.com/David-Haim/CountriesToCitiesJSON/master/countriesToCities.json")!
    let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithRequest(urlRequest) {
        (data, response, error) -> Void in

        let httpResponse = response as! NSHTTPURLResponse
        let statusCode = httpResponse.statusCode

        if (statusCode == 200) {

            do{

                let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)

                print (json)
            }catch {
                print("Error with Json: \(error)")
            }

        }
    }

    task.resume()

}

问题是我无法转向每个国家和每个城市,因为我不知道关键的>价值。我怎样才能转向每个国家和城市?

2 个答案:

答案 0 :(得分:0)

在此回复中,您可以找到有关国家和城市的所有数据。

您的回复是字典[String:[String]]类型。

示例:

部分回复:

let json = ["Eritrea":["Asmara",""],"Cuba":["Havana","Habana","La Habana","Matanzas","Villa","Bayamo","Cienfuegos","Santiago de Cuba","Holguín","Ciego de Ãvila","Pinar del Río","Sancti Spíritus","Camagüey","Las Tunas","Guantánamo","Varadero"],"Saint Helena":["Tristan Da Cunha","Jamestown"],"Christmas Island":["Flying Fish Cove"],"Ethiopia":["Addis Ababa","Awasa","Jijiga"],"British Indian Ocean Territory":[""]]

因此,如果您想获取所有国家/地区名称,请执行以下操作:

let keys = Array(json.keys)

如果您想以厄立特里亚为目标取城,请执行以下操作:

let cityes = json["Eritrea"]

答案 1 :(得分:0)

这里有一些Swift游乐场代码可以完全按照您的要求执行:

//: Playground - noun: a place where people can play
import UIKit
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

let urlStr = "https://raw.githubusercontent.com/David-Haim/CountriesToCitiesJSON/master/countriesToCities.json"

let requestURL: URL = URL(string: urlStr)!
let urlRequest: URLRequest = URLRequest(url: requestURL)
let session = URLSession.shared
let task = session.dataTask(with: urlRequest) {
    (data, response, error) -> Void in

    let httpResponse = response as! HTTPURLResponse
    let statusCode = httpResponse.statusCode

    if (statusCode == 200) {
        do{
            let json:[String:[String]] = try! JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! Dictionary
            for (country, cities) in json {
                print(country)
                for city in cities {
                    print("City in \(country): \(city)")
                }
            }


        }catch {
            print("Error with Json: \(error)")
        }

    } else {
        print("Other status: \(statusCode)")
    }
}

task.resume()

他们的关键是知道数据的格式,在这种情况下是包含String个键和String值数组的字典。声明json变量时,将其转换为实际变量:

let json:[String:[String]] = try! JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! Dictionary