使用Swift Collection Type来解析JSON

时间:2016-02-18 02:14:26

标签: arrays json swift parsing

我创建了一个UITableview来从github用户添加存储库的名称。这是我的代码:

import UIKit

class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

        var gits:[String] = []

        lazy var tableView:UITableView = {
            let tb = UITableView(frame: self.view.bounds, style: .Grouped)
            tb.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth]
            tb.delegate = self
            tb.dataSource = self
            tb.registerClass(UITableViewCell.self, forCellReuseIdentifier:"cell")
            return tb
        }()

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

        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
            let repoName = self.gits[indexPath.row]
            cell.textLabel?.text = repoName
            return cell
        }

        let jsonParser:(data:NSData)->[String] = {(data:NSData)->[String] in
            var result:[String]=[]
            do {
               let json = try NSJSONSerialization.JSONObjectWithData(data, options: [])
                for git in json as! NSArray {
                    result.append(git["full_name"] as! String)
                }
            } catch {

            }
            return result
        }

        func connectToServer(){
            let url = NSURL(string: "https://api.github.com/users/gazolla/repos")
            let request = NSMutableURLRequest(URL: url!)
            let config = NSURLSessionConfiguration.defaultSessionConfiguration()
            let session = NSURLSession(configuration: config)
            let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
                if (error != nil){
                    print("\(error)")
                    return
                }
                self.gits = self.jsonParser(data: data!)
                dispatch_sync(dispatch_get_main_queue(), { () -> Void in
                     self.tableView.reloadData()
                })
            }
            task.resume()
        }
        override func viewDidLoad() {
            super.viewDidLoad()

            self.view.addSubview(self.tableView)
            self.connectToServer()
        }

        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    }

当我编写json解析器时,我使用NSArray循环遍历json并使用强制转换来获取具有存储库名称的String。像他一样:

        let json = try NSJSONSerialization.JSONObjectWithData(data, options: [])
        for git in json as! NSArray {
            result.append(git["full_name"] as! String)
        }

我想使用swift集合来执行此操作,但我无法弄清楚我应该在Array中使用哪些数据类型。

从github返回的Json结构是这样的:

enter image description here

哪种类型可以在Swift Array中用来替换NSArray来解析这个json文件?

0 个答案:

没有答案