JSON序列化在swift中崩溃

Jes*_*win 12 nsjsonserialization swift

我一直在使用以下代码行来解析Objective-C中的JSON数据,但Swift中的相同内容会使应用程序崩溃.

NSDictionary* json = [NSJSONSerialization
                          JSONObjectWithData:_webData
                          options:kNilOptions
                          error:&error];
Run Code Online (Sandbox Code Playgroud)

我试过使用NSJSONReadingOptions.MutableContainers但似乎没有用.我已经使用在线发现的各种JSON有效性检查器验证了从Web服务器获取的JSON数据的有效性.

[编辑]我使用的swift代码如下:

let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
Run Code Online (Sandbox Code Playgroud)

[UPDATE]

使用let jsonResult: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary解决了这个问题.

Nat*_*ook 3

Xcode 给你的错误不是很有帮助,但看起来你需要以error不同的方式声明你的变量(更多信息请参见Apple的文档),然后确保你处理字典返回的情况nil

var error: AutoreleasingUnsafePointer<NSError?> = nil
let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data,
        options:NSJSONReadingOptions.MutableContainers,
        error: error) as? NSDictionary
if jsonResult {
    // process jsonResult
} else {
    // couldn't load JSON, look at error
}
Run Code Online (Sandbox Code Playgroud)