【发布时间】: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