SWIFT 2:遍历JSON数组

我从网址获取此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是一个字典数组,因此您可以使用

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

}

在 ,未指定的JSON类型已更改为Any

for anItem in jsonResult as! [Dictionary<String, Any>] { ... // or [[String:Any]]

以上是 SWIFT 2:遍历JSON数组 的全部内容, 来源链接: utcz.com/qa/399955.html

回到顶部