【发布时间】:2019-04-11 13:43:05
【问题描述】:
如何根据子节点中的值获取值。例如 如果我有这样的 JSON
{
"id": 14,
"name": "АBC",
"picture": 44,
"group": {
"id": 2,
"gname": "AAA",
"pic": 1
}
},
{
"id": 14,
"name": "АBC",
"picture": 44,
"group": {
"id": 1,
"gname": "BB",
"pic": 2
}
}...
]
我想获取子值为“AAA”的所有名称的列表
我知道如何读取 name 的所有值,但如果我只想要具有特定 gname 值的名称,我不知道如何读取它们。
代码如下:
import UIKit
import Alamofire
import SwiftyJSON
class ThirdViewController : UITableViewController {
var dataInfo = [[String: AnyObject]]()
let url = "http://XXX"
let header = ["X": "XXX"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.rowHeight = 50
getData(url: url)
self.tableView.reloadData()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataInfo.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as! Cell2
cell.lblName?.text = dataInfo[indexPath.row]["name"] as? String
return cell
}
func getData(url: String) {
Alamofire.request(url, method: .get, headers: header)
.responseJSON { response in
if response.result.isSuccess {
print("Sucess! Got the data")
let dataJSON : JSON = JSON(response.result.value!)
self.updateData(json: dataJSON)
} else {
print("Error: \(String(describing: response.result.error))")
}
}
self.tableView.reloadData()
}
func updateData(json : JSON) {
if let data = json[].arrayObject {
self.dataInfo = data as! [[String: AnyObject]]
self.tableView.reloadData()
}
else {
print("cannot connect to the server")
}
}
}
如果有人可以帮助我,我将不胜感激。
【问题讨论】:
-
不相关,但
viewDidLoad()和getData(末尾的行self.tableView.reloadData()毫无意义,因为调用函数时dataInfo为空。我们鼓励您使用Codable来解码数据。SwiftyJSON自 Swift 4 以来已过时。 -
谢谢您的信息先生。
标签: json xcode uitableview swift4