一尘不染

SWIFT 2:遍历JSON数组

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数组以在表视图的单元格中放置哪个名称?


阅读 364

收藏
2020-07-27

共1个答案

一尘不染

该变量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

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