Swift,NSJSONSerialization和NSError

问题是当有不完整的数据NSJSONSerialization.JSONObjectWithData崩溃的应用程序给意外地找到了零,同时解开一个可选的值错误,而不是通知我们使用NSError变量.所以我们无法防止崩溃.

你可以在下面找到我们使用的代码

var error:NSError? = nil

      let dataToUse = NSJSONSerialization.JSONObjectWithData(receivedData,options:   NSJSONReadingOptions.AllowFragments,error:&error) as NSDictionary

    if error != nil { println( "There was an error in NSJSONSerialization") }

到目前为止,我们无法找到工作.

问题是您之前投射JSON反序列化的结果
检查错误.如果JSON数据无效(例如不完整)则
NSJSONSerialization.JSONObjectWithData(...)

返回零和

NSJSONSerialization.JSONObjectWithData(...) as NSDictionary

会崩溃

这是一个正确检查错误情况的版本:

var error:NSError? = nil
if let jsonObject: AnyObject = NSJSONSerialization.JSONObjectWithData(receivedData,options: nil,error:&error) {
    if let dict = jsonObject as? NSDictionary {
        println(dict)
    } else {
        println("not a dictionary")
    }
} else {
    println("Could not parse JSON: \(error!)")
}

备注:

>检查错误的正确方法是测试返回值,而不是
错误变量.
> JSON阅读选项.AllowFragments在这里没有帮助.设置此选项
只允许例如不是NSArray或NSDictionary的实例的顶级对象

{ "someString" }

你也可以在一行中做一个可选的转换:

if let dict = NSJSONSerialization.JSONObjectWithData(receivedData,error:nil) as? NSDictionary {
    println(dict)
} else {
    println("Could not read JSON dictionary")
}

缺点是在其他情况下,您无法区分是否阅读JSON数据失败或JSON不代表字典.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...