SWIFT 2: Loop through JSON array

前端 未结 4 1353
孤城傲影
孤城傲影 2020-12-09 05:01

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

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

I want to display the n

相关标签:
4条回答
  • 2020-12-09 05:31

    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
    }
    

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

    for anItem in jsonResult as! [Dictionary<String, Any>] { ... // or [[String:Any]]
    
    0 讨论(0)
  • 2020-12-09 05:37

    If your is finally

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

    Updated:

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

    Updated:

    Make the JSON results in a DICT and get it with a loop "for (key, value)"

    0 讨论(0)
  • 2020-12-09 05:49
    let jsonResult: AnyObject? = NSJSONSerialization.JSONObjectWithData(data,
      options: NSJSONReadingOptions.AllowFragments,
      error:&parseError)
    
    0 讨论(0)
  • 2020-12-09 05:50

    make the JSON results in a DICT and get it with a loop "for (key, value)"

    0 讨论(0)
提交回复
热议问题