JSON String to NSDictionary from local JSON file

This tutorial will show you how to convert JSON string from a local JSON file into an NSDictionary (key-value pairs). I have also added catch blocks validation if something goes wrong.

    if let path = NSBundle.mainBundle().pathForResource("file", ofType: "json") {
        do {
            let jsonData = try NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMappedIfSafe)
            do {
                let jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
                    
                if let array : [NSDictionary] = jsonResult[city] as? [NSDictionary] {
                    // handle the array of key value pairs here!
                }
            } catch {}
        } catch {}
    }

Leave a Reply

Your email address will not be published. Required fields are marked *