【发布时间】:2021-04-30 23:01:27
【问题描述】:
我正在尝试将数据从 api 获取到我的表格视图中,但应用程序进入了 catch 错误“json 错误”。我会把代码分享给你。
class ViewController: UIViewController {
@IBOutlet weak var homeTableView: UITableView!
var repository = [RepositoryStats]()
override func viewDidLoad() {
super.viewDidLoad()
downloadJSON {
self.homeTableView.reloadData()
}
homeTableView.delegate = self
homeTableView.dataSource = self
}
func downloadJSON (completed: @escaping () -> ()) {
let url = URL (string: "https://api.github.com/search/repositories?q=language:Swift+language:RXSwift&sort=stars&order=desc")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error == nil {
do {
self.repository = try JSONDecoder().decode([RepositoryStats].self, from: data!)
DispatchQueue.main.async {
completed()
}
}catch {
print ("json error")
}
}
}.resume()
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return repository.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
cell.textLabel?.text = repository[indexPath.row].full_name
return cell
}
这是我声明的结构:
struct RepositoryStats: Decodable {
let items: [Item]
}
struct Item: Decodable {
let fullName: String
}
如果有人知道,为什么我会陷入“json 错误”捕获?谢谢!
链接:https://api.github.com/search/repositories?q=language:Swift+language:RXSwift&sort=stars&order=desc
【问题讨论】:
-
你得到它是因为你正在打印一个硬编码的字符串!如果您想要正确且有用的错误消息,请在
catch子句中执行print(error)。快速浏览一下 json 告诉我你缺少一个根元素,你不能从 json 消息的中间开始解码。您需要一个与消息的顶部(或最外层,如果您愿意)元素相对应的类型。 -
我使用了 print(error),我得到了这个。“希望解码 Array
,但找到了一个字典。”,underlyingError: nil))”。我想我需要做点什么使用那个“项目”,如果你打开链接,是这样的:“项目”:[ 之后是全名。你能帮我解决这个问题吗? -
这是我在第一条评论中试图解释的。创建一个包含项的新类型,该类型是您的类型的数组。然后在使用 JSONDecoder 时使用这个新类型
-
@JoakimDanielson 我改变了我的结构,但我得到了同样的错误。
-
RepositoryStats 是一个数组吗?
标签: json swift github-api