【发布时间】:2018-07-01 13:33:10
【问题描述】:
我正在从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
【问题讨论】: