SWIFT 2:遍历JSON数组 [英] SWIFT 2: Loop through JSON array

查看:135
本文介绍了SWIFT 2:遍历JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从URL获取此json,返回的JSON是:

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

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

我想在IOS的TableView中显示名称.

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

我的Swift2代码是:

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)

        }
    }
}

如何遍历JSON数组以在表视图的单元格中放置哪个名称?

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

推荐答案

变量jsonResult是字典数组,因此您可以使用

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

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

In Swift 3 the unspecified JSON type has been changed to Any

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

这篇关于SWIFT 2:遍历JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆