gpt4 book ai didi

json - Swift - JSON 解码返回空数组

转载 作者:行者123 更新时间:2023-11-28 05:40:21 25 4
gpt4 key购买 nike

对于我的第一个 Swift UIKit 应用程序,我试图解析一些 JSON 数据并使用它来填充 UITableView。理想情况下,表格 View 会随着 JSON 的更改而更新,但现在这并不是完全必要的,因为 JSON 很少更改。

但是我在解析 JSON 时遇到了一些问题 - 我似乎得到了一个空数组...

我的主视图 Controller 中的代码

import Foundation
import UIKit

//TODO - JSON

struct Visualisation: Codable {
var id: Int
let name, info, url_name, tags: String
}

/*
JSON:

[
{
"id": 0,
"name": "Two Body Collision",
"info": "A 2D body collision under the elastic collision assumption",
"url_name": "https://www.imperialvisualisations.com/visualisations/two-body-collision/two-body-collision/",
"tags": "Physics, Mechanics"

},
{
"id": 1,
"name": "Waves in Dielectrics",
"info": "The effect of incidence angle & refractive index of dielectric on reflection & transmission",
"url_name": "https://www.imperialvisualisations.com/visualisations/2d-and-3d-coordinate-systems/2d-polar-coordinates/",
"tags": "Physics, Maths, Matrices, Linear algebra"
}
]

This is the structure I am aiming for:

var visualisations: [Visualisation] = [
.init(id:0, name: "Two Body Collision", info: "A 2D body collision under the elastic collision assumption", url_name: "https://www.imperialvisualisations.com/visualisations/two-body-collision/two-body-collision/", tags: "Physics, Mechanics"),
.init(id:2, name: "Waves in Dielectrics", info: "The effect of incidence angle & refractive index of dielectric on reflection & transmission", url_name: "https://www.imperialvisualisations.com/visualisations/single-wave-in-3d/boundry-conditions/", tags: "Physics, Electromagnetism, Light, Refractive index, Angle of incidence")
]

*/

class ViewController: UIViewController {

@IBOutlet weak var tableView: UITableView!


var visualisations = [Visualisation]()

override func viewDidLoad() {
super.viewDidLoad()

guard let url = URL(string: "https://api.myjson.com/bins/1ao7in") else { fatalError("JSON URL not found") }

URLSession.shared.dataTask(with: url) { (data, _, _) in
guard let data = data else { fatalError("JSON data not loaded") }

guard let decodedVisualisations = try? JSONDecoder().decode([Visualisation].self, from: data) else { fatalError("Failed to decode JSON")}

DispatchQueue.main.async{
self.visualisations = decodedVisualisations
}

}.resume()

print("visualisations")
print(visualisations)

tableView.delegate = self
tableView.dataSource = self


navigationController?.navigationBar.prefersLargeTitles = true
title = "Visualisations"

}

}

extension ViewController: UITableViewDataSource, UITableViewDelegate {

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

//visualisation at row in view
let visualisation = visualisations[indexPath.row]
//recast! ??
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell") as! TableViewCell

cell.setCell(visualisation: visualisation)

//set Cell just sets the elements of the table cell in another file

return cell

}
}


我没有收到任何错误消息,但解码似乎对“可视化”数组没有任何作用。

如有任何帮助,我们将不胜感激 - 谢谢。

最佳答案

正如@vadian 评论的那样,这工作得很好。

struct Visualisation: Codable {
var id: Int
let name, info, url_name, tags: String
}

class ViewController: UIViewController {

var visualisations = [Visualisation]()

override func viewDidLoad() {
super.viewDidLoad()

guard let url = URL(string: "https://api.myjson.com/bins/1ao7in") else { fatalError("JSON URL not found") }

URLSession.shared.dataTask(with: url) { (data, _, _) in
guard let data = data else { fatalError("JSON data not loaded") }

do {
let decodedVisualisations = try JSONDecoder().decode([Visualisation].self, from: data)
self.visualisations = decodedVisualisations
} catch let error {
debugPrint(error.localizedDescription)
}
}.resume()

}
}

关于json - Swift - JSON 解码返回空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56995632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com