我一直在使用以下代码行在 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(数据,选项:NSJSONReadingOptions.MutableContainers,错误:错误)作为? NSDictionary
解决了这个问题。
最佳答案
Xcode 给你的错误不是很有帮助,但看起来你需要以不同的方式声明你的 error
变量 ( more at Apple's documentation ),然后确保你处理了这种情况字典返回 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
}
关于swift - JSON 序列化 swift 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24187826/