Skip to content

Instantly share code, notes, and snippets.

@slav123
Forked from santoshrajan/JSONParseDictionary.swift
Last active August 29, 2015 14:17
Show Gist options
  • Save slav123/bddef6d1cb34e85c3995 to your computer and use it in GitHub Desktop.
Save slav123/bddef6d1cb34e85c3995 to your computer and use it in GitHub Desktop.
// 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