Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在没有键的情况下解析JSON文件?_Json_Swift - Fatal编程技术网

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

如何在没有键的情况下解析JSON文件?,json,swift,Json,Swift,我已从以下url下载了JSON文件: 在将所有JSON文件解析为let JSON let requestURL: NSURL = NSURL(string: "https://raw.githubusercontent.com/David-Haim/CountriesToCitiesJSON/master/countriesToCities.json")! let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: re

我已从以下url下载了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()

}

问题是我不能求助于每个国家和城市,因为我不知道关键->价值。我怎样才能找到每个国家和城市?

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

您的响应是dictionary
[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"]
如果您想获取城市,例如厄立特里亚的城市,请执行以下操作:

let keys = Array(json.keys)
let cityes = json["Eritrea"]

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

您的响应是dictionary
[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"]
如果您想获取城市,例如厄立特里亚的城市,请执行以下操作:

let keys = Array(json.keys)
let cityes = json["Eritrea"]

下面是一些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

下面是一些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

可能重复查看在字典上迭代的Swift文档可能重复查看在字典上迭代的Swift文档其工作。非常感谢你。现在,我的作品清晰可见。非常感谢你。现在我明白了