Reputation: 402
I am trying to read a j.json file in my project folder. I get no errors when executing the code, but instead of print out, all I get is "null". The initial file extention was .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)
Update:
The problem was that I used rtf file (just as mentioned here). Here`s correct code.
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)
}
Upvotes: 0
Views: 182
Reputation: 48514
Good news first
jsonFilePath
, contentsOfFile
would failBad news
Where to go from here?
Defensively use let json = JSON(data: jsonData, options: .AllowFragments, error: &error)
and check the error. It is always good practice.
Which version of the SwiftyJSON are you using?
Installing SwiftyJSON (2.2.0)
Upvotes: 1