ios - 使用 Alamofire 和 Swift 3 反序列化复杂的 JSON

标签 ios json swift alamofire

如何反序列化此 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中不存在,您必须在Newsinit方法中编写(字典是[String:Any]而不是[string:String])

init(dictionary: [String:Any]) {
    self.title = dictionary["title"] ?? ""
}

关于ios - 使用 Alamofire 和 Swift 3 反序列化复杂的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44198327/

相关文章:

ios - tableview 单元格中的 Collection View 重新加载数据

c# - 如何正确地将 PHP 和 CURL 帖子转换为 groupon API 的 C# HTTP 客户端帖子

xcode - 在 SQLite.swift 的过滤器中使用变量

ios - 如何在辅助显示中显示 web View (具有所有交互),例如苹果电视

ios - 如何在 CoreSpotlight 的搜索结果中添加调用按钮?

iphone - 如何创建导航 Controller 以将主视图 Controller 连接到 2 个自定义 View Controller

javascript - 如何在 JavaScript 中编辑外部 JSON 文件?

jquery - 将json加载到变量中

ios - 如何在 Swift 2 的嵌套函数中设置全局函数的参数

iOS swift : How to calculate the sum of each value in a key-pair dictionary and store it in a separate dictionary?