Swift,NSJSONSerialization和NSError
发布时间:2020-12-14 05:42:54 所属栏目:百科 来源:网络整理
导读:问题是当有不完整的数据NSJSONSerialization.JSONObjectWithData崩溃的应用程序给意外地找到了零,同时解开一个可选的值错误,而不是通知我们使用NSError变量.所以我们无法防止崩溃. 你可以在下面找到我们使用的代码 var error:NSError? = nil let dataToUse =
问题是当有不完整的数据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!)") } 备注: >检查错误的正确方法是测试返回值,而不是 { "someString" } 你也可以在一行中做一个可选的转换: if let dict = NSJSONSerialization.JSONObjectWithData(receivedData,error:nil) as? NSDictionary { println(dict) } else { println("Could not read JSON dictionary") } 缺点是在其他情况下,您无法区分是否阅读JSON数据失败或JSON不代表字典. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |