我想从urlString获取JSON数据,但我不知道要放在jsonObj!.value(forKey: "") as?
中的值。如果你看一下JSON结构,它就没有主要名称来进入数据。
final let urlString = "https://api.coinmarketcap.com/v1/ticker/"
func downloadJsonWithURL() {
let url = NSURL(string: urlString)
URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
print(jsonObj!.value(forKey: ""))
if let actorArray = jsonObj!.value(forKey: "") as? NSArray {
for actor in actorArray{
if let actorDict = actor as? NSDictionary {
if let name = actorDict.value(forKey: "name") {
self.nameArray.append(name as! String)
}
if let name = actorDict.value(forKey: "rank") {
self.rankArray.append(name as! String)
}
}
}
}
OperationQueue.main.addOperation({
self.tableView.reloadData()
})
}
}).resume()
}
JSON结构
[
{
id: "bitcoin",
name: "Bitcoin",
symbol: "BTC",
rank: "1",
price_usd: "9361.68",
price_btc: "1.0",
24h_volume_usd: "9720310000.0",
market_cap_usd: "156442678736",
available_supply: "16710962.0",
total_supply: "16710962.0",
max_supply: "21000000.0",
percent_change_1h: "-1.11",
percent_change_24h: "-15.97",
percent_change_7d: "14.51",
last_updated: "1512057553"
}
]