Last active
August 29, 2015 14:07
-
-
Save santoshrajan/a84d73b42efdfc37af1c to your computer and use it in GitHub Desktop.
JSON Parse Dictionary in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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