【问题标题】:Swift JSON Parsing Access ArraySwift JSON 解析访问数组
【发布时间】: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

【问题讨论】:

    标签: json swift


    【解决方案1】:

    eleresults.results(或eletest)是results的数组。

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多