我向Blockchain API发出GET请求,这就是我得到的:
{
"USD": {
"15m": 1973.51,
"last": 1973.51,
"buy": 1973.51,
"sell": 1970.5,
"symbol": "$"
},
"ISK": {
"15m": 204455.64,
"last": 204455.64,
"buy": 204455.64,
"sell": 204143.8,
"symbol": "kr"
},
"HKD": {
"15m": 15400.36,
"last": 15400.36,
"buy": 15400.36,
"sell": 15376.88,
"symbol": "$"
},
"TWD": {
"15m": 59959.18,
"last": 59959.18,
"buy": 59959.18,
"sell": 59867.73,
"symbol": "NT$"
}
}
我尝试解析USD子对象,这是我的代码:
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error);
} else {
let responseData = String(data: data!, encoding: String.Encoding.utf8);
print(responseData);
var USD = [String]()
do{
if let ipString = NSString(data:data!, encoding: String.Encoding.utf8.rawValue) {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [NSDictionary];
USD = json.map { ($0 as! [String: AnyObject])["USD"] as! String }
}
}
catch{
print("Parse JSON failed")
}
}
})
但是当我运行它时,会出现错误:
无法将'__NSDictionaryM'类型的值转换为'NSArray'
我知道USD
更像[String:AnyObject]
,但它也不起作用。任何解决方案?
答案 0 :(得分:0)
这里没有你的json响应是数组类型,都是字典类型。这样做,希望它能解决你的问题:
var USD = [String: AnyObject]()
do{
if let ipString = NSString(data:data!, encoding: String.Encoding.utf8.rawValue) {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: AnyObject];
if let usd = json.["USD"] as? [String: AnyObject] {
USD = usd
}
}
}
catch{
print("Parse JSON failed")
}