【发布时间】:2017-05-26 09:39:47
【问题描述】:
如何反序列化这个 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,所以我知道我的请求没问题。问题是我不知道如何创建合适的数据模型。
【问题讨论】: