在swift中解析JSON数组 [英] Parsing JSON array in swift
问题描述
我正在尝试解析以下JSON
I am trying to parse the following 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,而我我正在使用以下代码来解析它:
This is the JSON I am getting from my web services, and I am using the following code to parse it:
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()
我收到以下错误
操作无法完成。 (NSURLErrorDomain错误-1005。)
致命错误:在解包可选值时意外发现nil
The operation couldn’t be completed. (NSURLErrorDomain error -1005.) fatal error: unexpectedly found nil while unwrapping an Optional value
我该如何解决这个问题?
how can I solve this?
推荐答案
您的网址返回以下JSON -
Your URL is returning the following 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会导致问题。
The outermost square brackets indicate that the root object is an array, so attempting to cast the result of your JSON parse to an NSDictionary causes problems.
您的代码应为 -
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()
这篇关于在swift中解析JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!