ios - 快速解析JSON数组

标签 ios json swift

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

相关文章:

ios - 为什么电话:* links don't work on ios?

ios - 将嵌套的 SCNNode 位置转换为屏幕空间中的 CGPoint

c# - 将 JSON 对象反序列化为数组

java - 如何在不出现 UnsatifiedLinkError 的情况下加载具有依赖项的 JNI .dylib 文件?

ios - swift 中 java 接口(interface)或 objective c 协议(protocol)的等价物是什么?

ios - 如何在 iTunes 中删除失败的 iOS 构建?这可能吗?

PHP <-> JavaScript 通信 : Am I stuck with ASCII?

json - Erlang JSON API 数据生命周期

ios - 使用非可选对象,而 swift 认为它是可选的

ios - 使用 UIPanGestureRecognizer 仅从两端调整 UIView 的大小