我正在尝试解析以下 JSON
[
{
"id": "5",
"name": "Test",
"team1": "thingy team",
"team2": "clicky team",
"category": "4",
"end_date": "1415217600",
"cat_name": "new thingy",
"team1_bets": 1,
"team2_bets": 1
}
]
这是我从网络服务中获取的 JSON,我正在使用以下代码解析它:
let urlAsString = "http://codespikestudios.com/betting_app/bet/get_events/4"
//let urlAsString = "http://api.topcoder.com/v2/challenges?pageSize=2"
let url: NSURL = NSURL(string: urlAsString)!
let urlSession = NSURLSession.sharedSession()
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
if (error != nil) {
println(error.localizedDescription)
}
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if (err != nil) {
println("JSON Error \(err!.localizedDescription)")
}
println(jsonTime)
})
jsonQuery.resume()
我收到以下错误
The operation couldn’t be completed. (NSURLErrorDomain error -1005.) fatal error: unexpectedly found nil while unwrapping an Optional value
我该如何解决这个问题?
最佳答案
您的网址返回以下 JSON -
[
{
"id": "5",
"name": "Test",
"team1": "thingy team",
"team2": "clicky team",
"category": "4",
"end_date": "1415217600",
"cat_name": "new thingy",
"team1_bets": 1,
"team2_bets": 1
}
]
最外面的方括号表示根对象是一个数组,因此尝试将 JSON 解析的结果转换为 NSDictionary 会导致问题。
你的代码应该是 -
let urlAsString = "http://codespikestudios.com/betting_app/bet/get_events/4"
let url: NSURL = NSURL(string: urlAsString)!
let urlSession = NSURLSession.sharedSession()
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
if (error != nil) {
println(error.localizedDescription)
}
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSArray?
if (err != nil) {
println("JSON Error \(err!.localizedDescription)")
}
println(jsonResult!)
})
jsonQuery.resume()
关于ios - 快速解析JSON数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26840203/