15

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 names in a TableView on IOS.

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)

        }
    }
}

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

4 Answers 4

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]]
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Do you mean: let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as NSDictionary
0

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)"

2 Comments

Thanky you. But can you explain a little bit more?
you make the array in a dict[key:value]. if your jsonResult is simply an array only.
0
let jsonResult: AnyObject? = NSJSONSerialization.JSONObjectWithData(data,
  options: NSJSONReadingOptions.AllowFragments,
  error:&parseError)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.