Swift,NSJSONSerialization和NSError [英] Swift, NSJSONSerialization and NSError
问题描述
问题是,当有不完整的数据时,NSJSONSerialization.JSONObjectWithData
使应用程序崩溃并给出unexpectedly found nil while unwrapping an Optional value
错误,而不是使用NSError变量通知我们.因此,我们无法防止崩溃.
The problem is when there is incomplete data NSJSONSerialization.JSONObjectWithData
is crashing the application giving unexpectedly found nil while unwrapping an Optional value
error instead of informing us using NSError variable. So we are unable to prevent crash.
您可以在下面找到我们正在使用的代码
You can find code we are using below
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") }
到目前为止,我们无法找到解决方法.
Till now we are unable to find a work around.
推荐答案
问题是您将JSON反序列化的结果强制转换为之前 检查错误.如果JSON数据无效(例如不完整),则
The problem is that you cast the result of the JSON deserialization before checking for an error. If the JSON data is invalid (e.g. incomplete) then
NSJSONSerialization.JSONObjectWithData(...)
返回nil
和
NSJSONSerialization.JSONObjectWithData(...) as NSDictionary
将崩溃.
这是一个可以正确检查错误情况的版本:
Here is a version that checks for the error conditions correctly:
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
实例的顶级对象,例如
- The correct way to check for an error is to test the return value, not the error variable.
The JSON reading option
.AllowFragments
does not help here. Setting this option only allows that top-level objects that are not an instance ofNSArray
orNSDictionary
, for example
{ "someString" }
您还可以使用可选强制转换 as?
:
if let dict = NSJSONSerialization.JSONObjectWithData(receivedData, options: nil, error:nil) as? NSDictionary {
println(dict)
} else {
println("Could not read JSON dictionary")
}
缺点是,在else
情况下,您无法区分是否阅读
JSON数据失败或JSON不代表字典.
The disadvantage is that in the else
case you cannot distinguish whether reading
the JSON data failed or if the JSON did not represent a dictionary.
有关Swift 3的更新,请参见 LightningStryk的答案.
For an update to Swift 3, see LightningStryk's answer.
这篇关于Swift,NSJSONSerialization和NSError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!