gpt4 book ai didi

json - Swift JSON 解析访问数组

转载 作者:行者123 更新时间:2023-11-28 14:32:47 24 4
gpt4 key购买 nike

我正在从 Open - Elevation 中提取一个 JSON 文件但是,我无法从我提取的数据中访问数组的各个部分。我当前的 View Controller 中有 JSON 解析代码,它还允许我读取它自己的整个数组。

struct ElevationArray: Decodable {
let results: [results]
}

struct results: Decodable {
let latitude: Double
let longitude: Double
let elevation: Double

init(json: [String: Any]){
latitude = json["latitude"] as? Double ?? 0.0
longitude = json["longitude"] as? Double ?? 0.0
elevation = json["elevation"] as? Double ?? 0.0

}
}

class FlightInfo: UITableViewController {


@IBOutlet weak var Lat: UILabel!
@IBOutlet weak var Long: UILabel!
@IBOutlet weak var Elevation_label: UILabel!

var elevationmain: Double?

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Lat.text = "\(publocation.latitude)"
Long.text = "\(publocation.longitude)"

ElevationJSON()


}


override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

func ElevationJSON(){

let jsonURLString = "https://api.open-elevation.com/api/v1/lookup?locations=41.161758,-8.583933"
guard let url = URL(string: jsonURLString) else {return}

URLSession.shared.dataTask(with: url) { (data, response, err) in
//perhaps check err
//also perhaps check response status 200 OK

guard let data = data else { return }


do {
//let websiteDescription = try JSONDecoder().decode(WebsiteDescription.self, from: data)
// print(websiteDescription.name, websiteDescription.description)

let eleresults = try JSONDecoder().decode(ElevationArray.self, from: data)
print(eleresults.results)

let eletest = eleresults.results

print(eletest)

//self.elevationmain = Double(eleresults.results)
} catch let jsonErr {
print("Error serializing json:", jsonErr)
}



}.resume()
}

}

这是我运行应用程序并打印出数组时得到的控制台输出。 enter image description here

最佳答案

eleresults.results(或 eletest)是一个 results 数组。

要访问所有数据,请使用循环:

for result in eletest {
print(result.elevation)
}

如果您只想要第一个结果:

if let result = eletest.first {
print(result.elevation)
}

顺便说一句 - 你的 results 结构应该重命名为有用的东西,比如 Elevation 或者比 results 更详细的描述(注意它应该开始带有大写字母。

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

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