【发布时间】:2014-06-12 15:06:24
【问题描述】:
我一直在使用以下代码行在 Objective-C 中解析 JSON 数据,但在 Swift 中同样的代码会导致应用程序崩溃。
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:_webData
options:kNilOptions
error:&error];
我尝试使用NSJSONReadingOptions.MutableContainers,但似乎不起作用。我已经使用网上找到的各种 JSON 有效性检查器验证了从 Web 服务器获取的 JSON 数据的有效性。
[编辑] 我使用的 swift 代码如下:
let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
[更新]
使用let jsonResult: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary 可以解决问题。
【问题讨论】:
-
您不能将
nil与 NS_OPTIONS 样式的枚举一起使用 -NSJSONReadingOptions.fromMask(0)将为您提供该选项类型的“以上都不是”值。 -
记住
+JSONObjectWithData:...的返回类型是id,而不是NSDictionary*。例如,该方法可以返回NSArray*或nil。