【问题标题】:How I can decode and access Double from JSON using Alamofire and Swift Decode如何使用 Alamofire 和 Swift Decode 从 JSON 解码和访问 Double
【发布时间】:2020-03-18 17:19:55
【问题描述】:

我尝试使用 Alamofire 和 Swift 解码来解码和访问特定货币的特定汇率:

这是我的模型:

    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"
    }
}

这是 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")
    }

到目前为止一切顺利,但我无法访问单一货币及其汇率值。我想用来自 JSON 的 JPY 汇率值声明一个变量“JPYrate”。你能帮我导航吗?

【问题讨论】:

  • 你试过 st.rates["JPY"] 吗?
  • 我认为你需要进一步解释你的问题是什么,这样我们才能正确地帮助你。 “访问失败”非常模糊。
  • 旁白:不要打印"error"(字符串)。 print(error) 看看到底出了什么问题。

标签: ios swift alamofire decode


【解决方案1】:

你可以像这样简单地从ratesDictionary获取键JPY对应的值,

let JPYrate = st.rates["JPY"]

另外,如果键名与属性名相同,则无需创建enum CodingKeys。所以,你的struct Listek 看起来像,

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

【讨论】:

  • 谢谢你,完全正确,你帮了我很多
【解决方案2】:

exchangeratesapi 似乎发送一致的数据。如果是这样,我的建议是将费率解码为专用结构

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
}

那你就可以直接得到费率了

print(st.rates.JPY)

【讨论】:

    【解决方案3】:

    首先,您可以创建一个计算属性来访问日元汇率:

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

    或者按照@vadian 的建议将费率解析为特定类型。

    其次,您可以使用Alamofire的responseDecodable方法自动解码。

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

    【讨论】:

      猜你喜欢
      • 2023-04-02
      • 1970-01-01
      • 2018-11-12
      • 2017-01-20
      • 1970-01-01
      • 1970-01-01
      • 2019-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多