json - 将 json 解析为 swift 常量

标签 json swift

我正在尝试解析来自端点的所有数据并将其分配给常量,以便我可以在 ViewController 类中使用它们。我最大的问题是将“key”数组的每一项分配给常量。谁能帮帮我吗?

 static func fetchRates(completionHandler: (current: [Currency]) -> ()) {

    let urlString = "https://api.bitcoinaverage.com/ticker/all"
    let url = NSURL(string: urlString)
    NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (location, response, error) -> Void in

        do {
            let json = try(NSJSONSerialization.JSONObjectWithData(location!, options: .MutableContainers))
            let tickerData = [Currency]()

            for key in json as! [String : AnyObject] {

             }

            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                completionHandler(current: tickerData)
            })

        } catch let err as NSError {
            print(err)
        }

    }).resume()
  }

这是来自端点的响应。

  {
"AUD": {
 "24h_avg": 621.17,
 "ask": 624.12,
 "bid": 620.3,
"last": 620.45,
"timestamp": "Mon, 23 May 2016 20:01:16 -0000",
"total_vol": 671.28
 },
 "BRL": {
"24h_avg": 1725.77,
"ask": 1748.83,
"bid": 1731.8,
"last": 1738.64,
"timestamp": "Mon, 23 May 2016 20:01:16 -0000",
"total_vol": 534.19
 },
 "CAD": {
"24h_avg": 579.2,
"ask": 579.27,
"bid": 573.57,
"last": 577.42,
"timestamp": "Mon, 23 May 2016 20:01:16 -0000",
"total_vol": 413.81
 },

最佳答案

尝试一下:

for (key, value) in (json as! [String: AnyObject]) {
    let currencyData = value as! [String: AnyObject]
    // key is the currency code: AUD, BRL, etc
    // currencyData is the details: ask, bid, last, ...
}

关于json - 将 json 解析为 swift 常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37398337/

相关文章:

javascript - 如何使用express返回数据响应?

objective-c - 当函数的类不继承自 NSObject 时,从 ObjC 调用一个 swift 实例函数

swift - 将导航 backBarButtonItem 设置为转到 Swift 中的特定 UIViewController

ruby-on-rails - 如何用 Oj gem 替换 Ruby 中的 to_json?

swift - Rxswift + Moya + Moya-ObjectMapper 错误处理

ios - tableView 数据源的字典

ios - 如何修复此错误 : 'Foundation._GenericObjCError error 0. '

arrays - 存储在 jsonb 中的数组的 Postgres 总和

php - 我的 php 代码转换了一些字符

json - golang json 解码 map[string]interface{} 的一部分