Skip to content

Instantly share code, notes, and snippets.

@santoshrajan
Last active August 29, 2015 14:07
Show Gist options
  • Save santoshrajan/a84d73b42efdfc37af1c to your computer and use it in GitHub Desktop.
Save santoshrajan/a84d73b42efdfc37af1c to your computer and use it in GitHub Desktop.
JSON Parse Dictionary in Swift
// Author - Santosh Rajan
import Foundation
let string = "{\"name\": \"John\", \"age\": 35, \"children\": [\"Jack\", \"Jill\"]}"
func JSONParseDictionary(jsonString: String) -> [String: AnyObject] {
if let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding) {
if let dictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: nil) as? [String: AnyObject] {
return dictionary
}
}
return [String: AnyObject]()
}
let dictionary = JSONParseDictionary(string)
let name = dictionary["name"] as String // John
let age = dictionary["age"] as Int // 35
let firstChild = dictionary["children"]?[0] as String // Jack
let secondChild = dictionary["children"]?[1] as String // Jill
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment