Krivvenz Krivvenz - 10 months ago 23
Swift Question

Reading in a JSON File Using Swift

I'm really struggling with trying to read a JSON file into Swift so I can play around with it. I've spent the best part of 2 days re-searching and trying different methods but no luck as of yet so I have signed up to StackOverFlow to see if anyone can point me in the right direction.....

My JSON file is called test.json and contains the following:

"name": "Bob",
"age": "16",
"employed": "No"
"name": "Vinny",
"age": "56",
"employed": "Yes"

The file is stored in the documents directly and I access it using the following code:

let file = "test.json"
let dirs : String[] = NSSearchPathForDirectoriesInDomains(
true) as String[]

if (dirs != nil) {
let directories: String[] = dirs
let dir = directories[0]
let path = dir.stringByAppendingPathComponent(file)

var jsonData = NSData(contentsOfFile:path, options: nil, error: nil)
println("jsonData \(jsonData)" // This prints what looks to be JSON encoded data.

var jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: nil) as? NSDictionary

println("jsonDict \(jsonDict)") - This prints nil.....

If anyone can just give me a push in the right direction on how I can de-serialize the JSON file and put it in an accessible Swift object I will be eternally grateful!

Kind Regards,



Follow the below code :

if let path = NSBundle.mainBundle().pathForResource("test", ofType: "json")
    if let jsonData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)
        if let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary
            if let persons : NSArray = jsonResult["person"] as? NSArray
                // Do stuff

The array "persons" will contain all data for key person. Iterate throughs to fetch it.