0

我在解码时遇到问题。JSON尝试获取日出和日落时间,但没有任何效果。帮助

func getData(latitude: String,longtitude: String) {
    let url = URL(string: "https://api.sunrise-sunset.org/json?lat=\(latitude)&lng=\(longtitude)")
    Alamofire.request(url!).responseJSON { (response) in
        print(response)
        guard let data = response.data else { return }
        do {
            let st = try JSONDecoder().decode(results.self, from: data)
            print(st.sunrise)
        }
        catch {
            print("error")
        }
    }
}
4

1 回答 1

0

你需要的是一个像这样解码的根结构

struct Root : Decodable {
   let status: String
   let results: results
}

struct results: Decodable {
    let sunrise : string 
    //other struc proporties as well in here 
let astronomical_twilight_end: String
}

所以你可以这样做

let root = try JSONDecoder().decode(Root.self, from: data)

让结果 = root.result

于 2018-07-09T21:08:31.863 回答