简体   繁体   English

我如何使用 Alamofire 和 Swift Decode 从 JSON 解码和访问 Double

[英]How I can decode and access Double from JSON using Alamofire and Swift Decode

I try do decode and access specific exchange rate for specific currency using Alamofire and Swift decode:我尝试使用 Alamofire 和 Swift 解码来解码和访问特定货币的特定汇率:

this is my model:这是我的模型:

    struct Listek: Codable {
    let base: String
    let date: String
    let rates: [String: Double]

    enum CodingKeys: String, CodingKey {
        case base = "base"
        case date = "date"
        case rates = "rates"
    }
}

this is Alamofire API call + decode这是 Alamofire API 调用 + 解码

let apiToContact = "https://api.exchangeratesapi.io/latest"
    AF.request(apiToContact).responseJSON { (response) in
    print(response)
    guard let data = response.data else { return }
    do {
    let st = try JSONDecoder().decode(Listek.self, from: data)
        print (st.rates)
        print (st.base)
        print (st.date)

    }
    catch {
    print("error")
    }

So far so good, but I fail in accessing the single currency and its rate value.到目前为止一切顺利,但我无法访问单一货币及其汇率值。 I would like declare a variable "JPYrate" with value of JPY rate from JSON.我想声明一个变量“JPYrate”,其中包含来自 JSON 的 JPY rate 值。 Can you please navigate me?你能帮我导航吗?

You can simply get the value corresponding to key JPY from rates Dictionary like so,您可以简单地从rates Dictionary获取与关键JPY对应的值,如下所示,

let JPYrate = st.rates["JPY"]

Also, there is no need to create enum CodingKeys , if the key names are same as the property names.此外,如果键名与属性名相同,则无需创建enum CodingKeys So, your struct Listek looks like,所以,你的struct Listek看起来像,

struct Listek: Codable {
    let base: String
    let date: String
    let rates: [String:Double]
}

exchangeratesapi seems to send consistent data. exchangeratesapi似乎发送一致的数据。 if so my suggestion is to decode the rates into a dedicated struct如果是这样,我的建议是将费率解码为专用结构

struct Listek: Decodable {
    let base: String
    let date: String
    let rates: Rates
}

struct Rates: Decodable {
    let CAD, HKD, ISK, PHP, DKK, HUF, CZK, AUD, RON, SEK, IDR, INR, BRL, RUB, HRK, JPY, THB, CHF, SGD, PLN, BGN, TRY, CNY, NOK, NZD, ZAR, USD, MXN, ILS, GBP, KRW, MYR : Double
}

Then you can get the rate directly然后就可以直接拿到费率了

print(st.rates.JPY)

First, you can make a computed property to access the JPY rate:首先,您可以创建一个计算属性来访问日元汇率:

var jpyRate: Double? { rates["JPY"] }

Or parse the rates into a specific type as recommended by @vadian.或者按照@vadian 的建议将费率解析为特定类型。

Second, you can use Alamofire's responseDecodable method to do the decoding automatically.其次,您可以使用 Alamofire 的responseDecodable方法自动进行解码。

AF.request(apiToContact).responseDecodable(of: Listek.self) { response in
    debugPrint(response)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM