【问题标题】:Parsing JSON into tableview将 JSON 解析为 tableview
【发布时间】:2015-11-23 20:04:50
【问题描述】:

我正在从远程服务器接收 JSON 文件,我可以在标签中显示结果。当我调用函数processJSONData() 时,JSON 数据工作正常,并且 tableview 与简单数组一起工作正常。如何合并两者以在 tableview 中显示 JSON 文件的结果?请查看下面的代码并进行编辑。非常感谢:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var countryLabel: UILabel!
    @IBOutlet weak var capitalLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        //processJSONData()
                  self.myTableView.registerClass(UITableViewCell.self,forCellReuseIdentifier: "cell")
        self.myTableView.dataSource = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func processJSONData(){
        let urlPath = "http://dubaisinan.host22.com/service1.php"
        let url : NSURL = NSURL(string: urlPath)!
        let session = NSURLSession.sharedSession()

        let task = session.dataTaskWithURL(url,completionHandler: {(data, respose, error) -> Void in
            if error != nil {
                println(error)
            }
            else {
                    self.abc(data)
            }
        })
        task.resume()
    }


    func abc(data:NSData)
    {
        var parseError: NSError?

        let result:AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &parseError);

        if(parseError == nil){
            if let dictResult = result as? NSArray{

                dispatch_async(dispatch_get_main_queue()) {
                self.countryLabel.text = dictResult[2]["Capital"] as? String
                }
            }
        }
    }

    @IBOutlet weak var myTableView: UITableView!

    var items = ["One","Two", "Three","Four"]

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


    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:UITableViewCell = self.myTableView

        .dequeueReusableCellWithIdentifier("cell") as UITableViewCell

        cell.textLabel?.text = self.items[indexPath.row]
        return cell
    }
}

【问题讨论】:

  • 这个问题令人困惑。您只是想在表格视图单元格中添加或使用其他字段和数据吗?
  • 嗨迈克尔,我只想将远程数据库中的以下 JSON 结果显示到表格视图中:[{"Country":"Canada","Capital":"Otawa"},{"Country ":"法国","首都":"巴黎"},{"国家":"英格兰","首都":"伦敦"}]。就像我提到的,JSON 文件工作正常,其中一项可以显示在标签中。如何在表格视图中显示信息?谢谢。
  • 这完全取决于您希望单元格的外观以及您希望它们显示什么信息。在问题中发布您的示例 JSON,并可能显示您希望表格单元格的外观。

标签: ios json swift uitableview


【解决方案1】:

我没有看到您将解析结果分配给全局“项目”并在任何地方使用新数据重新加载 tableview。

可以在这里完成

if let dictResult = result as? NSArray{
    self.items = dictResult
    self.myTableView.reloadData()

///the rest of the code
            }

【讨论】:

    【解决方案2】:

    您必须将 JSON 数据保存到类级变量中,您将在任何函数之外定义该变量,类似于您定义“项目”的方式。假设您有一个包含每个国家首都的国家/地区列表,这可能如下所示:

    var countryAndCapitalData = [(country: String, capital: String)]()
    

    这可以通过首先定义一个结构来包含您的数据来改进:

    struct CountryInfo
    {
        name: String
        capital: String
        init(name:String, capital:String)
        {
            self.name = name
            self.capital = capital
        }
    }
    

    它允许您将数据数组定义为 CountryInfo 数组:

    var countryAndCapitalData = [CountryInfo]()
    

    然后在您的“abc”函数(我坚持将其重命名为类似 processCountryData)中,将国家名称 + 大写名称字符串对存储在 countryAndCapitalData 中。例如:

    countryAndCapitalData.append(CountryInfo(countryName, capitalName))
    

    使用 For 循环遍历 dictResult 中的值。创建 countryName 和 capitalName 取决于 JSON 的结构,但从您的示例来看,它可能如下所示:

    for countryDictionary in dictResult[2]
    {
        if let countryName = countryDictionary["country"], let capitalName = countryDictionary["capital"]
        {
            countryAndCapitalData.append(CountryInfo(countryName, capitalName))
        }
    }
    

    然后在 tableView.cellForRowAtIndexPath 中,用countryAndCapitalData[indexPath.row].namecountryAndCapitalData[indexPath.row].capital 填充单元格标签。

    最后,请务必在循环后重新加载表格(感谢 Eugene):

    dispatch_async(dispatch_get_main_queue()) {
        self.myTableView.reloadData()
    }
    

    对任何编译错误深表歉意,因为我是从 Windows 机器上输入的。

    【讨论】:

    • 谢谢 Skypecakes。能否请您编辑上述代码以插入建议的修改。
    • 您试一试如何让我们知道您遇到了什么问题?如果你自己做,你会更好地理解它。
    • 谢谢你的skypecakes。 self.myTableView.reloadData() 解决了这个问题。
    【解决方案3】:

    您应该在abc 方法调用中更新您的items 属性,然后刷新表格:

    func abc(data: NSData) {
       // Do something with data
       items = .. // processed data
    }
    
    var items: [String]? {
        didSet {
            NSOperationQueue.mainQueue.addOperationWithBlock {
                self.tableView.reloadData()
            }
        }
    }
    

    【讨论】:

    • 其实我喜欢这种优雅的方式:注意:reloadData() 应该在主线程上调用!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多