如何反序列化此 JSON 并在 tableView 中显示标题 JSON:https://www.healthcare.gov/api/articles.json
到目前为止我已经尝试过:
struct News {
let title : String
init(dictionary: [String:String]) {
self.title = dictionary["mainTitle"] ?? ""
}
}
var newsData = [News]()
func downloadData() {
Alamofire.request("https://www.healthcare.gov/api/articles.json").responseJSON { response in
print(response.request as Any)
print(response.response as Any)
print(response.data as Any)
print(response.result.value)
self.newsData.removeAll()
if let json = response.result.value as? [[String:String]] {
for news in json {
self.newsData.append(News(dictionary: news))
}
self.tableView.reloadData()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
downloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return newsData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let news = newsData[indexPath.row]
cell.textLabel?.text = news.title
return cell
}
服务器状态代码是 200,所以我知道我的请求没问题。问题是我不知道如何创建正确的数据模型。
最佳答案
JSON 令人困惑,因为在 articles
数组的末尾(应该只包含字典)有一个 bool 值 false
,因此向下转换为 [[String:Any]]
失败。
您必须 flatMap
数组才能忽略 Bool
if let json = response.result.value as? [String:Any],
let articles = json["articles"] as? [Any] {
for news in articles.flatMap({$0 as? [String:Any]}) {
self.newsData.append(News(dictionary: news))
}
self.tableView.reloadData()
}
并且键mainTitle
在JSON中不存在,您必须在News
的init
方法中编写(字典是[String:Any]
而不是[string:String]
)
init(dictionary: [String:Any]) {
self.title = dictionary["title"] ?? ""
}
关于ios - 使用 Alamofire 和 Swift 3 反序列化复杂的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44198327/