Last active
August 29, 2015 14:23
-
-
Save jaisontj/e73c2eb58f0a42b94a06 to your computer and use it in GitHub Desktop.
JSONParser with mods for Swift 2.0
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
import Foundation | |
let string = "[ {\"name\": \"John\", \"age\": 21}, {\"name\": \"Bob\", \"age\": 35} ]" | |
func JSONParseArray(string: String) -> [AnyObject]{ | |
if let data = string.dataUsingEncoding(NSUTF8StringEncoding){ | |
do{ | |
if let array = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? [AnyObject] { | |
return array | |
} | |
}catch{ | |
print("error" | |
//handle errors here | |
} | |
} | |
return [AnyObject]() | |
} | |
for element: AnyObject in JSONParseArray(string) { | |
let name = element["name"] as? String | |
let age = element["age"] as? Int | |
print("Name: \(name), Age: \(age)") | |
} | |
/* Prints following | |
Name: Optional(John), Age: Optional(21) | |
Name: Optional(Bob), Age: Optional(35) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment