Last active
November 30, 2019 18:49
-
-
Save santoshrajan/597a6099442211985b76 to your computer and use it in GitHub Desktop.
JSON Parse Array 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\": 21}, {\"name\": \"Bob\", \"age\": 35} ]" | |
func JSONParseArray(jsonString: String) -> [AnyObject] { | |
if let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding) { | |
if let array = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: nil) as? [AnyObject] { | |
return array | |
} | |
} | |
return [AnyObject]() | |
} | |
for elem: AnyObject in JSONParseArray(string) { | |
let name = elem["name"] as String | |
let age = elem["age"] as Int | |
println("Name: \(name), Age: \(age)") | |
} | |
/* Prints following | |
Name: John, Age: 21 | |
Name: Bob, Age: 35 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment