Swift 到 Swift 3 次代码转换:读取 JSON 个文件
Swift to Swift 3 code conversions: Reading JSON files
我有这段代码可以读取 JSON 文件,我正在尝试将这些文件移入 Swift 3 环境。这是:
do {
let dictionary = try NSJSONSerialization.JSONObjectWithData(dataOK, options: NSJSONReadingOptions()) as AnyObject!
dictionaryOK = (dictionary as! NSDictionary as? Dictionary <String, AnyObject>)!
}
catch {
print("Level file '\(filename)' is not valid JSON: \(error)")
return nil
}
Xcode 给出了修复一些错误的建议(因为一些对象和 类 已被重命名),结果是:
do {
//Problem here: parameters don't match overrides
let dictionary = try JSONSerialization.jsonObject(dataOK as Data, options: JSONSerialization.ReadingOptions()) as AnyObject!
dictionaryOK = (dictionary as! NSDictionary as? Dictionary <String, AnyObject>)!
}
catch {
print("Level file '\(filename)' is not valid JSON: \(error)")
return nil
}
它不匹配任何 jsonObjects 覆盖(它说)。我检查了文档,其中说 jsonObjects 的参数应该是:
class func jsonObject(with data: Data,
options opt: JSONSerialization.ReadingOptions = []) throws -> AnyObject
我做错了什么?
您的 Swift 2 代码一开始就非常冗长。
试试这个:
do {
if let dictionaryOK = try JSONSerialization.jsonObject(with: dataOK, options: []) as? [String: AnyObject] {
// parse JSON
}
} catch {
print(error)
}
我有这段代码可以读取 JSON 文件,我正在尝试将这些文件移入 Swift 3 环境。这是:
do {
let dictionary = try NSJSONSerialization.JSONObjectWithData(dataOK, options: NSJSONReadingOptions()) as AnyObject!
dictionaryOK = (dictionary as! NSDictionary as? Dictionary <String, AnyObject>)!
}
catch {
print("Level file '\(filename)' is not valid JSON: \(error)")
return nil
}
Xcode 给出了修复一些错误的建议(因为一些对象和 类 已被重命名),结果是:
do {
//Problem here: parameters don't match overrides
let dictionary = try JSONSerialization.jsonObject(dataOK as Data, options: JSONSerialization.ReadingOptions()) as AnyObject!
dictionaryOK = (dictionary as! NSDictionary as? Dictionary <String, AnyObject>)!
}
catch {
print("Level file '\(filename)' is not valid JSON: \(error)")
return nil
}
它不匹配任何 jsonObjects 覆盖(它说)。我检查了文档,其中说 jsonObjects 的参数应该是:
class func jsonObject(with data: Data,
options opt: JSONSerialization.ReadingOptions = []) throws -> AnyObject
我做错了什么?
您的 Swift 2 代码一开始就非常冗长。
试试这个:
do {
if let dictionaryOK = try JSONSerialization.jsonObject(with: dataOK, options: []) as? [String: AnyObject] {
// parse JSON
}
} catch {
print(error)
}