【问题标题】:SwiftyJSON reading file - nullSwiftyJSON 读取文件 - null
【发布时间】:2015-07-15 08:17:21
【问题描述】:

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

【问题讨论】:

  • 你检查过j.json文件的内容是一个有效的JSON吗?
  • 这是我的初始文件。我将其名称和扩展名更改为“j.json”(不确定是否导致问题)。 dropbox.com/s/atfq1gtptrt4ojf/jsonResponse.rtf?dl=0
  • NSError 实例传递给error 参数,那么您可能会收到错误

标签: ios json swift swifty-json


【解决方案1】:

好消息第一

  1. 你的代码是正确的
  2. 你会不会得到一个错误的jsonFilePathcontentsOfFile 会失败

坏消息

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

从这里到哪里去?

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

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

    安装 SwiftyJSON (2.2.0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    • 2019-01-30
    相关资源
    最近更新 更多