Swift 4.Decodable + alamofire

时间:2018-01-30 00:54:59

标签: json swift alamofire decodable

我在解码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")
        }
    }
}

1 个答案:

答案 0 :(得分: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