swift - JSON 序列化 swift 崩溃

标签 swift nsjsonserialization

我一直在使用以下代码行在 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/

相关文章:

ios - JSON 写入中的顶级类型无效

java - 将 Swift 数据转换为 Int16

objective-c - Decimal 在 Swift 3 中作为 NSDecimal 而不是 NSDecimalNumber 导入到 Objective C

ios - 如何在 iOS 上正确读取 JSON

ios - 在 iOS 中使用 NSJSONSerialization 是否有数据限制?

ios - NSJSON序列化和表情符号

ios - NSURLSessionDownloadTaskDelegate JSON 响应

swift - 如何使用 Swift 3 正确实现静态单元格

arrays - SwiftyJSON 将新数据附加到现有 JSON 数组

ios - 如何以编程方式填充 switch case 值?