ios - SwiftyJSON 读取文件 - 空

标签 ios json swift swifty-json

我正在尝试读取项目文件夹中的 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)
       }

最佳答案

好消息先来

  1. 您的代码正确
  2. 如果 jsonFilePath 错误,contentsOfFile 将会失败

坏消息

  1. 格式不正确的 json?好像没有。您的示例解析正确
  2. 我已经使用您的代码 + json 成功创建了一个应用程序,并且它可以正确解析。我没有收到错误。

从这里去哪里?

  1. 防御性地使用 let json = JSON(data: jsonData, options: .AllowFragments, error: &error) 并检查错误。这始终是一个好的做法。

  2. 您使用的是哪个版本的 SwiftyJSON?

    Installing SwiftyJSON (2.2.0)

关于ios - SwiftyJSON 读取文件 - 空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31425042/

相关文章:

java - 使用java将java字符串转换为geojson

java - Jackson json反序列化,根元素来自json

ios - 如何将 UIActivityIndi​​catorView 放在导航栏按钮 (rightBarButtonItem/leftBarButtonItem) 的顶部

ios - NSOperationQueue addOperations waitUntilFinished

swift - 具有字典参数的 Realm 中的谓词

iOS 扩展和 cordova : 'Cordova/CDV.h' file not found

ios - 将 UISegmentedControl 放置在按钮栏中

iOS 游戏开发

objective-c - 为什么当我的应用程序处于后台时,关闭模拟器会使我的应用程序收到SIGTERM?

javascript - 如果对象包含 JavaScript 中的字母,如何返回对象