将JSON解析为tableview(Parsing JSON into tableview)

编程入门 行业动态 更新时间:2024-10-28 12:23:07
JSON解析为tableview(Parsing JSON into tableview)

我从远程服务器收到一个JSON文件,我可以在标签中显示结果。 当我调用函数processJSONData()并且tableview适用于一个简单的数组时,JSON数据工作正常。 如何将两者合并以显示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 } }

I am receiving a JSON file from a remote server and I can display the result in a label. The JSON data is working fine when I call function processJSONData() and the tableview works fine with a simple array. How can I incorporate both to display the result from the JSON file in the tableview? Kindly look at the code below and edit. Many thanks:

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数据保存到类级变量中,您将在任何函数之外定义该变量,类似于您定义“items”的方式。 假设您有一个具有每个资本的国家/地区列表,这可能是这样的:

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].name和countryAndCapitalData[indexPath.row].capital填充单元格标签。

最后,确保在循环之后重新加载表(感谢Eugene):

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

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

You have to save the JSON data into a class-level variable, which you will define outside of any function, similar to how you defined "items". Assuming you have a list of countries with the capital of each, this might look like so:

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

This could be improved by first defining a struct to contain your data:

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

which lets you define your data array as an array of CountryInfo:

var countryAndCapitalData = [CountryInfo]()

Then in your "abc" function (which I insist you rename to something like processCountryData), store the pairs of country name + capital name strings in countryAndCapitalData. For example:

countryAndCapitalData.append(CountryInfo(countryName, capitalName))

Use a For loop to loop through values in dictResult. Creating countryName and capitalName depends on the structure of your JSON, but from your example it might look like this:

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

Then in tableView.cellForRowAtIndexPath, populate the cell label(s) with countryAndCapitalData[indexPath.row].name and countryAndCapitalData[indexPath.row].capital.

And finally, be sure to reload the table after the loop (thanks Eugene):

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

Apologies for any compilation errors, as I'm typing this from a Windows machine.

更多推荐

本文发布于:2023-08-05 20:08:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1439391.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:JSON   tableview   Parsing

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!