0

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)
       }
Community
  • 1
  • 1
driver733
  • 401
  • 2
  • 6
  • 21
  • 1
    did you checked the content of `j.json` file is a valid JSON? – Akhilrajtr Jul 15 '15 at 08:21
  • Here`s my initial file. I changed its name and extention to "j.json" (not sure if it caused a problem). https://www.dropbox.com/s/atfq1gtptrt4ojf/jsonResponse.rtf?dl=0 – driver733 Jul 15 '15 at 08:36
  • pass an `NSError` instance to the `error` parameter, then you probably get an error – vadian Jul 15 '15 at 08:38

1 Answers1

1

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)

Community
  • 1
  • 1
SwiftArchitect
  • 47,376
  • 28
  • 140
  • 179