【发布时间】:2015-10-25 12:11:15
【问题描述】:
我设法在 Swift 中解析了一些 JSON,但我有点挣扎。我需要从“事件”属性中提取“标题”字符串。我有“Hasta”和“Location”,这对我(初学者)有好处。所以,现在我试图用这 3 个属性填充一个 tableview。到目前为止,tableview 是空的,并且没有显示我的信息。有什么帮助吗?请记住,我是一个相对初学者 - 欢迎仔细解释。我一直在使用 SwiftyJSON 来解析 JSON。我已经给我的代码解释性标记。作为参考,我有一个变量 = var TableData = String。
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 {
do {
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 (_, 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 {
self.TableData.append(hasta)
//print(hasta)
}
// Check if string for key "Location" exists
if let location = subJson["Location"].string {
self.TableData.append(location)
//print(location)
}
}
}
} catch {
print("In catch block")
}
}
}
}
task.resume()
}
这是我尝试填充表格的方式(如下)。我意识到我需要制作一个带有 3 个标签的自定义单元格。但就目前而言,是否可以只使用 3 个中的任何一个填充 tableview,看看它是否有效。
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.TableData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = self.TableData[indexPath.row]
return cell
}
【问题讨论】:
-
那么,有什么想法吗? :)
-
删除了大量的换行符以提高可读性
-
谢谢...但是有人愿意帮忙吗?
标签: json swift parsing tableview