【问题标题】:How to download data from JSON to table view when JSON is an Array of Dictionary?当 JSON 是字典数组时,如何将数据从 JSON 下载到表视图?
【发布时间】:2017-06-22 11:52:08
【问题描述】:

我是 Swift 新手,正在学习如何将 JSON 数据下载到表格视图中。该代码在编译时不会显示任何错误,但会在运行时显示。 JSON数据链接:https://jsonplaceholder.typicode.com/comments

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 100
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! show
        let loadingInBackground = DispatchQueue(label: "loadingInBackground", qos: .background)

        loadingInBackground.async {

            let stringURL = "https://jsonplaceholder.typicode.com/comments"
            let urlFromString = URL(string: stringURL)

            var request = URLRequest(url: urlFromString!)
            request.httpMethod = "GET"

            let session = URLSession(configuration: URLSessionConfiguration.default)
            session.dataTask(with: request) { (data, response, error) in

                do {
                    let dataInJSON = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [ [String: Any] ]

                    print(dataInJSON)

                    let arrayOf_dataInJSON = dataInJSON[indexPath.row]

                    cell.id.text = arrayOf_dataInJSON["id"] as! String?
                    cell.email.text = ("email: \(arrayOf_dataInJSON["email"] as! Int?)")

                }catch{print(error)}

                }.resume()
        }
        return cell
    }


}

class show : UITableViewCell {
    @IBOutlet var id: UILabel!
    @IBOutlet var email: UILabel!
}

错误是:“无法将 '__NSCFNumber' (0x10e7c1540) 类型的值转换为 'NSString' (0x10b679c40)

我收到错误:“cell.id.text = arrayOf_dataInJSON["id"] as!String?

【问题讨论】:

  • "id": 1 是一个数字,你将它强制转换为一个字符串,除了崩溃,你期望发生什么?
  • 请告诉我如何解决这个问题@luk2302
  • 好吧,我是这个@NiravD 的新手。
  • @RajeevKulariya 试试这个cell.id.text = "\(arrayOf_dataInJSON["id"] as? Int ?? 0)"

标签: swift


【解决方案1】:

试试"\(arrayOf_dataInJSON["id"] as? Int ?? 0)"

【讨论】:

  • 感谢@Salman,该应用程序运行良好,但有时它只是崩溃并在我使用“JSONSerialization”的行上给出错误“EXC_BAD_INSTRUCTION”。我现在该怎么办?
  • @RajeevKulariya let dataInJSON = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [ [String: Any] ]
  • 我不知道是谁拒绝了答案,你说的“显示你点击服务的代码”是什么意思
  • 我知道,但是,在这里我们可以提供参考,您必须了解这一点,当它带有可选时,用户知道它。我们假设问卷对语言有基本的了解..!!!!
  • @EricAya 当你出生时,你是在一分钟内开始跑步的还是什么?我是IOS新手,我还在学习。好的。
【解决方案2】:
it "\(arrayOf_dataInJSON["id"])" 

这将显示 Optional(1),Optional(2),... 可选类型,以便您可以展开

cell.textLabel?.text = "(arrayOf_dataInJSON["id"] as!NSNumber)"

【讨论】:

  • 它显示此错误:“无法将类型 'NSNumber' 的值分配给类型 'String?' "
猜你喜欢
  • 1970-01-01
  • 2018-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-12
  • 2020-12-14
  • 2021-07-31
  • 2021-06-14
相关资源
最近更新 更多