swift2 SWIFT 2:通过JSON数组循环

r8uurelv  于 2022-11-06  发布在  Swift
关注(0)|答案(4)|浏览(216)

我从一个url中得到这个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数组以将哪个名称放入表视图的单元格中?

evrscar2

evrscar21#

变量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]]
mwg9r5ms

mwg9r5ms2#

在DICT中生成JSON结果,并使用循环“for(key,value)”获取它

nle07wnf

nle07wnf3#

如果你终于

let jsonResult = [{"id":1,"name":"Mary"},{"id":2,"name":"John"}]
var jsonDictResult[String: Int] = jsonResult;

更新日期:

let jsonResult: AnyObject? = NSJSONSerialization.JSONObjectWithData(data,
    options: NSJSONReadingOptions.AllowFragments,
    error:&parseError)

更新日期:

DICT中生成JSON结果,并使用循环***“for(key,value)"***获取该结果

u0njafvf

u0njafvf4#

let jsonResult: AnyObject? = NSJSONSerialization.JSONObjectWithData(data,
  options: NSJSONReadingOptions.AllowFragments,
  error:&parseError)

相关问题