user3163404 user3163404 - 5 months ago 30
JSON Question

SWIFT 2: Loop through JSON array

I am getting this json from a url, the return JSON is:

[{"id":1,"name":"Mary"},{"id":2,"name":"John"}]


I want to display the names in a TableView on IOS.

My Swift2 Code is:

class ViewController: UIViewController, UITableViewDelegate {

var NumberOfPersons = 0

var NameOfPerson = [String]()

override func viewDidLoad() {
super.viewDidLoad()

parseJSON()

}

func parseJSON(){

do {

let data = NSData(contentsOfURL: NSURL(string: "http://zzzzzz.com/API/name.php")!)

let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)

let NumberOfPersons = jsonResult.count

**LOOP THROUGH THE JSON ARRAY**

} catch let error as NSError {

print(error)

}
}
}


How can I loop through the JSON array to put which name in a cell on a Table View?

Thanks

SOLVED by @vadian

for anItem in jsonResult as! [Dictionary<String, AnyObject>] {
let personName = anItem["name"] as! String
let personID = anItem["id"] as! Int
// do something with personName and personID
}

Answer

The variable jsonResult is an array of dictionaries, so you can loop through the array with

for anItem in jsonResult as! [Dictionary<String, AnyObject>] {
  let personName = anItem["name"] as! String
  let personID = anItem["id"] as! Int
// do something with personName and personID
}