driver733
driver733

Reputation: 402

SwiftyJSON reading file - null

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

Answers (1)

SwiftArchitect
SwiftArchitect

Reputation: 48514

Good news first

  1. Your code is correct
  2. Would you get either a wrong jsonFilePath, contentsOfFile would fail

Bad news

  1. Malformed json? It seems not. Your sample parses properly
  2. I have successfully created an app using your code + your json and it parses properly. I did not get an error.

Where to go from here?

  1. Defensively use let json = JSON(data: jsonData, options: .AllowFragments, error: &error) and check the error. It is always good practice.

  2. Which version of the SwiftyJSON are you using?

    Installing SwiftyJSON (2.2.0)

Upvotes: 1

Related Questions