简体   繁体   中英

How do I load a local JSON file into a uitableview in swift?

I've been trying to look for how to do it, but still have not been successful. I want to put a JSON file into a tableview

{
  "person":[
       {
         "name": "John",
         "age": "17",
       },
       {
         "name": "Bob",
         "age": "23",             
       }

   ]
}    

You can get the details from the json string as follows.

let listDetails = json["Person"] as? Array<[String:String]>)!

and you can have your table view delegates as follows.

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // Return the number of sections.
    return 1
}


override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // Return the number of rows in the section.
    return listDetails.count
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("yourCellIdentifier", forIndexPath: indexPath)

    let dict = listDetails[indexPath.row] as? [String:String]
    let name = dict["name"]
    let age = dict["age"]

    //now assign this name and age to the textViews you have in your tableView.

    return cell
}    

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM