我从网址获取此json,返回的JSON为:
[{"id":1,"name":"Mary"},{"id":2,"name":"John"}]
我想在IOS的TableView中显示名称。
我的Swift2代码是:
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) } } }
如何遍历JSON数组以在表视图的单元格中放置哪个名称?
该变量jsonResult是一个字典数组,因此您可以使用
jsonResult
for anItem in jsonResult as! [Dictionary<String, AnyObject>] { // or [[String:AnyObject]] let personName = anItem["name"] as! String let personID = anItem["id"] as! Int // do something with personName and personID }
在 Swift 3中 ,未指定的JSON类型已更改为Any
Any
for anItem in jsonResult as! [Dictionary<String, Any>] { ... // or [[String:Any]]