我正在从Open - Elevation提取JSON文件,但是无法从提取的数据访问数组的各个段。我当前的视图控制器中包含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
答案 0 :(得分:1)
eleresults.results
(或eletest
)是results
的数组。
要访问所有数据,请使用循环:
for result in eletest {
print(result.elevation)
}
如果您只想要第一个结果:
if let result = eletest.first {
print(result.elevation)
}
顺便说一句-您的results
结构应重命名为有用的内容,例如Elevation
或除results
以外的更多描述(请注意,它应以大写字母开头。