小编典典

快速解析JSON数组

json

我正在尝试解析以下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
    }
]

这是我从Web服务获取的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()

我收到以下错误

该操作无法完成。(NSURLErrorDomain错误-1005。)致命错误:在展开可选值时意外发现nil

我该如何解决?


阅读 332

收藏
2020-07-27

共1个答案

小编典典

您的网址返回了以下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()
2020-07-27