Swift 当JSON是一个字典数组时,如何将数据从JSON下载到表视图?
我是Swift新手,正在学习如何将JSON数据下载到表视图中。代码在编译时不显示任何错误,但在运行时显示。JSON数据链接: 错误是:“无法将类型为'\u NSCFNumber'(0x10e7c1540)的值强制转换为'NSString'(0x10b679c40)” 我在以下行中遇到错误:“cell.id.text=arrayOf\u dataInJSON[“id”]as!String?”尝试一下Swift 当JSON是一个字典数组时,如何将数据从JSON下载到表视图?,swift,Swift,我是Swift新手,正在学习如何将JSON数据下载到表视图中。代码在编译时不显示任何错误,但在运行时显示。JSON数据链接: 错误是:“无法将类型为'\u NSCFNumber'(0x10e7c1540)的值强制转换为'NSString'(0x10b679c40)” 我在以下行中遇到错误:“cell.id.text=arrayOf\u dataInJSON[“id”]as!String?”尝试一下“\(arrayOf\u dataInJSON[“id”]as?Int??0)” 这将显示可选(1)
“\(arrayOf\u dataInJSON[“id”]as?Int??0)”
这将显示可选(1)、可选(2)和,。。。可选类型,以便可以展开
cell.textlab?.text=“(arrayOf_dataInJSON[“id”]as!NSNumber)”
“id”:1
是一个数字,你强制将其转换为字符串,除了崩溃之外,你还期望发生什么?请告诉我如何解决这个问题@luk2302我对这个@NiravD是新手。@RajeevKulariya像这样尝试cell.id.text=“\(arrayOf_dataInJSON[“id”]as?Int??0)“
谢谢@Salman,该应用程序运行良好,但有时它会崩溃,并在我使用“JSONSerialization”的行中给出错误“EXC\u BAD\u指令”。我现在该怎么办?@RajeevKulariya让dataInJSON=试试JSONSerialization.jsonObject(with:data!,options:JSONSerialization.ReadingOptions.allowFragments)as![[String:Any]]
我不知道是谁低估了答案,你所说的“在你点击服务的地方显示代码”是什么意思。我知道,但是,在这里,我们可以提供参考,你必须理解这一点,用户知道这一点,当它与可选选项一起出现时。我们假设问卷对语言有基本的了解@埃里卡娅你出生的时候,你是不是一分钟后就开始跑步了?我是IOS新手,我还在学习。好的。它显示此错误:“无法将“NSNumber”类型的值分配给“String”类型”
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!
}
it "\(arrayOf_dataInJSON["id"])"