我正在尝试解析来自端点的所有数据并将其分配给常量,以便我可以在 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/