解析URL中的JSON数据并显示在表视图中

时间:2016-01-05 16:19:01

标签: json swift uitableview

这是数据放置在URL的方式

{
"studentsinfo": [
    {
            "id": "100",
            "name": "Adam",
            "email": "adam@example.com",
            "address": "House #33, ABC Lane, ABC CITY 06987",
            "gender" : "male",
            "phone": {
                "mobile": "+1 1234567890",
                "home": "00 123456",
                "office": "00 321654"
            }
    },
    {
            "id": "101",
            "name": "Archbould",
            "email": "archbould@example.com",
            "address": "House #33, ABC Lane, ABC CITY 06987",
            "gender" : "male",
            "phone": {
                "mobile": "+1 1234567890",
                "home": "00 123456",
                "office": "00 321654"
            }
    }
}

我必须下载并在桌面视图中显示。到目前为止,我已经能够下载整个快照但无法下载特定节点的数据。

这是我的代码:

 let urlAsString = "https://raw.githubusercontent.com/mobilesiri/JSON-Parsing-in-Android/master/index.html"
    let url = NSURL(string: urlAsString)!
    let urlSession = NSURLSession.sharedSession()

    //2
    let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
        if (error != nil) {
            println(error.localizedDescription)
        }
        var err: NSError?

        // 3
        var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
        if (err != nil) {
            println("JSON Error \(err!.localizedDescription)")
        }

        // 4

    println(jsonResult)


        dispatch_async(dispatch_get_main_queue(), {

        })
    })
    // 5
    jsonQuery.resume()
}

现在我的问题是如何下载特定节点数据并在表格视图中显示它。

1 个答案:

答案 0 :(得分:0)

完成以下实施。

  • 创建一个包含所有这些属性的Object,对于每个属性 字典应该有等效的对象。制作那些数组 objects。将数据添加到该索引处每个对象的每个单元格中。

  • 另请参阅以下链接

    gist.github.com/Starefossen/689428b6c532d7fec0bb

要点内容:

import UIKit
import Foundation
import XCPlayground

XCPSetExecutionShouldContinueIndefinitely()

class RemoteAPI {
    func getData(completionHandler: ((NSArray!, NSError!) -> Void)!) -> Void {
        let url: NSURL = NSURL(string: "http://itunes.apple.com/search?term=Turistforeningen&media=software")
        let ses = NSURLSession.sharedSession()
        let task = ses.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
            if (error != nil) {
                return completionHandler(nil, error)
            }

            var error: NSError?
            let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary

            if (error != nil) {
                return completionHandler(nil, error)
            } else {
                return completionHandler(json["results"] as [NSDictionary], nil)
            }
        })
        task.resume()
    }
}

var api = RemoteAPI()

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    var tableView: UITableView!
    var items: NSMutableArray = []

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.frame = CGRect(x: 0, y: 0, width: 320, height: 480)
        self.tableView = UITableView(frame:self.view!.frame)
        self.tableView!.delegate = self
        self.tableView!.dataSource = self
        self.tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
        self.view?.addSubview(self.tableView)

        api.getData({data, error -> Void in
            if (data != nil) {
                self.items = NSMutableArray(array: data)
                self.tableView!.reloadData()
                self.view
            } else {
                println("api.getData failed")
                println(error)
            }
        })
    }

    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
        return self.items.count;
    }

    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
        let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")

        if let navn = self.items[indexPath.row]["trackName"] as? NSString {
            cell.textLabel.text = navn
        } else {
            cell.textLabel.text = "No Name"
        }

        if let desc = self.items[indexPath.row]["description"] as? NSString {
            cell.detailTextLabel.text = desc
        }

        return cell
    }
}

ViewController().view