我正在尝试读取项目文件夹中的 j.json 文件。执行代码时我没有收到任何错误,但我得到的只是“null”,而不是打印出来。初始文件扩展名为 .rtf。
let jsonFilePath:NSString = NSBundle.mainBundle().pathForResource("j", ofType: "json")!
let jsonData:NSData = NSData(contentsOfFile: jsonFilePath as String, options: .DataReadingMappedIfSafe, error: nil)!
let json = JSON(data: jsonData)
println(json)
更新:
问题是我使用了 rtf 文件(正如提到的 here )。这是正确的代码。
let jsonFilePath:NSString = NSBundle.mainBundle().pathForResource("<INPUT FILE NAME>", ofType: "<FILE EXTENTION>")!
let jsonData:NSData = NSData(contentsOfFile: jsonFilePath as String, options: .DataReadingMappedIfSafe, error: nil)!
var error:NSError?
let json = JSON(data: jsonData, options: .AllowFragments, error: &error)
if error != nil{
println(error!.localizedDescription)
}
else{
println(json)
}
最佳答案
好消息先来
- 您的代码正确
- 如果
jsonFilePath
错误,contentsOfFile
将会失败
坏消息
- 格式不正确的 json?好像没有。您的示例解析正确
- 我已经使用您的代码 + json 成功创建了一个应用程序,并且它可以正确解析。我没有收到错误。
从这里去哪里?
防御性地使用
let json = JSON(data: jsonData, options: .AllowFragments, error: &error)
并检查错误。这始终是一个好的做法。您使用的是哪个版本的 SwiftyJSON?
Installing SwiftyJSON (2.2.0)
关于ios - SwiftyJSON 读取文件 - 空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31425042/