问题是当有不完整的数据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数据无效(例如不完整)则
检查错误.如果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不代表字典.