【问题标题】:Parse JSON Swift TableView解析 JSON Swift TableView
【发布时间】:2015-10-24 15:38:52
【问题描述】:

我想从这个 JSON URL (https://www.kimonolabs.com/api/7flcy3qm?apikey=gNq3hB1j0NtBdAvXJLEFx8JaqtDG8y6Y) 中提取“Event”、“Hasta”和“Location”,但我不知道该怎么做?谁能帮我?这是我的代码...然后我想用这 3 个填充一个表格视图。

override func viewDidLoad() {
    super.viewDidLoad()

    splitViewController!.preferredDisplayMode = UISplitViewControllerDisplayMode.AllVisible

    UINavigationBar.appearance().barTintColor = UIColor(red: 52.0/255.0, green: 170.0/255.0, blue: 220.0/255.0, alpha: 1.0)
    UINavigationBar.appearance().tintColor = UIColor.whiteColor()
    UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()]

    let url = NSURL(string:"https://www.kimonolabs.com/api/7flcy3qm?apikey=gNq3hB1j0NtBdAvXJLEFx8JaqtDG8y6Y")!
    let session = NSURLSession.sharedSession()

    let task = session.dataTaskWithURL(url) { (data, response, error) -> Void in
        if error != nil {
            print(error)
        } else {
            if let data = data {
                do {
                    let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
                    if jsonResult!.count > 0 {
                        if let results = jsonResult!["results"] as? NSDictionary, collection2 = results["collection2"] as? NSArray {
                            for entry in collection2 {
                                if let dict = entry["Event"] as? NSDictionary {
                                    print(dict)
                                }

                                else if let array = entry as? NSArray {

                                } else {

                                }
                            }

                            if let items = jsonResult?["Date"] as? NSArray {
                                print(items)

                            }
                        }
                    }
                } catch {
                    print("In catch block")
                }
            }
        }
    }
    task.resume()
}

【问题讨论】:

    标签: ios json swift parsing tableview


    【解决方案1】:

    用 Swift 解析 JSON 简直就是地狱。您可以使用SwiftyJSON 轻松做到这一点。

    使用您的 JSON:

    // Get content of json url
    let jsonString = try NSString.init(contentsOfURL: url!, encoding: NSUTF8StringEncoding)
    
    // Create JSON object from data
    let json = JSON(data: jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!)
    
    // Check if array for key "collection2" exists
    if let collection2 = json["results"]["collection2"].array {
        // Create JSON array from it and loop for each object
        for (key, subJson):(String, JSON) in JSON(collection2) {
            // Check if dictionary for key "Event" exists
            if let event = subJson["Event"].dictionary {
                 print(event)
            }
    
            // Check if string for key "Hasta" exists
            if let hasta = subJson["Hasta"].string {
                 print(hasta)
            }
    
            // Check if string for key "Location" exists
            if let location = subJson["Location"].string {
                 print(location)
            }
        }
    }
    

    【讨论】:

    • 优秀的 Kientux。非常感谢。是的,用 Swift 解析它是一场噩梦!
    • 请问如何用“Event”、“Hasta”和“Location”的文本填充表格视图?
    • 在collection2中循环后,可以将所有subJson存储到NSArray。然后使用UITableView 显示带有UITableViewDelegateUITableViewDataSource 的数据。有很多关于如何在 iOS 中创建表格视图的好教程。你应该四处寻找。
    【解决方案2】:

    我创建了这个在线实用程序 (http://www.json4swift.com),它将您的 json 转换为您可以像这样轻松操作的快速可表示模型:

    // Get content of json url
    let jsonString = try NSString.init(contentsOfURL: url!, encoding: NSUTF8StringEncoding)
    
    // Create JSON Dictionary from data
                var jsonResult = NSJSONSerialization.JSONObjectWithData(jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
    
            //Create instance for base model representation
            let responseModel = Json4Swift_Base(dictionary: jsonResult)
    
            //print name
            print(responseModel!.name)
    
            //Get the collection2 from result
            let collection2 = responseModel?.results!.collection2
    
            //Get the first object from collection 2
            let firstObject = collection2?.first
    
            //Print the event and hesta
            print(firstObject?.event?.text)
            print(firstObject?.hasta)
    

    如果是表格视图,您将实现委托方法 cellForRowAtIndexPath

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
        var cell = tableView.dequeueReusableCellWithIdentifier("YourCellIdentifier")
    
        if cell == nil {
            cell = UITableViewCell()
        }
    
        //Assuming you have responseModel instantiated earlier
        let collection2 = responseModel?.results!.collection2!
    
        //Get the n'th object from collection 2
        let object = collection2[indexPath.row]
    
        //Populate the cell the event and hesta
        cell.textLabel?.text =  object?.event?.text
        cell.detailTextLabel?.text = object?.hasta
    
        return cell
    }
    

    免责声明:将以上内容视为伪代码,未经实际测试,但可以为您提供有关处理的想法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多