【问题标题】:Error anexing JSON data with Swift 2使用 Swift 2 合并 JSON 数据时出错
【发布时间】:2015-12-03 17:08:34
【问题描述】:

我正在使用 iOS 应用程序(使用 Swift2),我遇到了一些问题,包括应用程序的 JSON 数据。对于“注册”,我使用手机号码验证(如 whatsapp),所以当我使用以下 JSON 数据(http://data.okfn.org/data/core/country-codes/r/country-codes.json)在 tableView 中显示每个国家和拨号代码时,它显示错误。

我正在编写这段代码:


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    let urlPath = "http://data.okfn.org/data/core/country-codes/r/country-codes.json"
    let url = NSURL(string: urlPath)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithURL(url!, completionHandler: { data, response, error -> Void in
        if (error != nil) {
            print(error)
        } else {
            do {
                let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
                print(jsonResult["name"])
            } catch _ {}
        }
    })
    task.resume()
}

}


调试区显示如下:


    {
    DS = AL;
    Dial = 355;
    FIFA = ALB;
    FIPS = AL;
    GAUL = 3;
    IOC = ALB;
    "ISO3166-1-Alpha-2" = AL;
    "ISO3166-1-Alpha-3" = ALB;
    "ISO3166-1-numeric" = 008;
    ITU = ALB;
    MARC = aa;
    WMO = AB;
    "currency_alphabetic_code" = ALL;
    "currency_country_name" = ALBANIA;
    "currency_minor_unit" = 2;
    "currency_name" = Lek;
    "currency_numeric_code" = 008;
    "is_independent" = Yes;
    name = Albania;
    "name_fr" = Albanie;
},

那么,有没有其他方法可以只访问国家名称和拨号代码?我不知道为什么它显示一个错误/nil

谢谢!

【问题讨论】:

    标签: ios arrays json swift dictionary


    【解决方案1】:

    jsonResult 是一个字典数组。数组不能被key下标,导致报错。

    替换do - catch 部分的此代码打印所有国家/地区的名称和拨号代码。字典类型甚至可以限制为[String:String]

    do {
       let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [[String:String]]
       for country in jsonResult {
          print(country["name"]!, country["Dial"]!)
       }
    } catch let error as NSError { print(error) }
    

    【讨论】:

      猜你喜欢
      • 2013-11-17
      • 2015-02-17
      • 2014-10-02
      • 1970-01-01
      • 1970-01-01
      • 2019-06-13
      • 2019-01-01
      • 2016-08-27
      • 1970-01-01
      相关资源
      最近更新 更多