【问题标题】:JSONSerialization and EXC_BAD_ACCESSJSONSerialization 和 EXC_BAD_ACCESS
【发布时间】:2015-03-08 00:25:47
【问题描述】:

我在 php 服务的帮助下从 MYSQL 数据库中获取一些信息。最后,我将它通过echo json_encode($resultArray) 推送到我的应用程序。现在我遇到了 JSONSerialization 的问题,这是我的代码。

If ( urlData != nil ) {
        let res = response as NSHTTPURLResponse!;

        NSLog("Response code: %ld", res.statusCode);

        if (res.statusCode >= 200 && res.statusCode < 300)
        {
            var responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!

            NSLog("Response ==> %@", responseData);

            var error: NSError?

            let jsonData2:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary

            let success:NSInteger = jsonData2.valueForKey("IdUser") as NSInteger
            ...

使用此代码,我在NSJSONSerialization 的行中收到错误消息EXC_BAD_ACCESS。有人知道为什么吗?

responseDate 有这个示例值:

[{"IdUser":"2","preName":"Max","lastName":"Muster"}]

提前致谢。

【问题讨论】:

  • 我找到了解决方案。当响应数据有括号时,序列化不起作用。这是正常的还是有办法在 xcode 中处理?
  • 向我们展示响应数据。并告诉我们 error NSJSONSerialization 正在返回什么。

标签: ios json swift nsjsonserialization


【解决方案1】:

您的 JSON 响应不是 NSDictionary。它是一个数组。现在这个数组有一个项目,它本身就是一个字典。但是你必须先解析数组:

let array = NSJSONSerialization.JSONObjectWithData(urlData!, options:nil, error: &error) as NSArray

如果要获取字典,则从数组中获取第一项:

let dictionary = array[0] as NSDictionary

如果您想要来自IdUser 的字段值,则获取该字符串值,然后调用integerValue

let idUser = dictionary["IdUser"]?.integerValue

顺便说一句,如果响应的格式可能存在偏差,您可能需要小心解析响应,使用可选绑定来优雅地处理您期望格式的数据缺失,例如:

var error: NSError?
if let array = NSJSONSerialization.JSONObjectWithData(urlData!, options:nil, error: &error) as? [[String: AnyObject]] {
    if let dictionary = array.first {
        if let idUser = dictionary["IdUser"]?.integerValue {
            // `IdUser` definitely found; now check the value here
        }
    }
}

【讨论】:

    【解决方案2】:

    一种快速解析 json 的简单方法,使用 SwiftyJSON 但如果你不想要它,你可以这样做

    if let jsonData2 = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: nil)  as? AnyObject {
    
            }
    

    但我强烈建议使用SwiftyJSON

    【讨论】:

    • 除非你想尝试对 SwiftyJSON 对象进行排序——你需要转换回 NSArray/NSDictionary。这很慢……因为它,我实际上已经停止使用 SwiftyJSON。本机对象要快得多。如果需要排序,不要使用 Swifty JSON!
    猜你喜欢
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-16
    • 2012-02-07
    相关资源
    最近更新 更多