0

При GET запросе с сервера я получаю такой ответ:

   "disclaimer": "Usage subject to terms: https://openexchangerates.org/terms",
  "license": "https://openexchangerates.org/license",
  "timestamp": 1665594000,
  "base": "USD",
"rates": {
    "AED": 3.67295,
    "AFN": 85.5,
    "ALL": 119.95,
}

Хочу его подстроить под себя, привести его к такому виду:

"disclaimer": "Usage subject to terms: https://openexchangerates.org/terms",
  "license": "https://openexchangerates.org/license",
  "timestamp": 1665594000,
  "base": "USD",
  "rates": [
    {
        "key":  "AED"
        "value": 3.76295
    },
    {
        "key":  "AFN"
        "value": 85.5
    },
    {
        "key":  "ALL"
        "value": 119.95
    }
  ]

Как мне это сделать?

1 ответ 1

1

Если вы хотите как-то изменить структуру получаемых данных, то можно это сделать с помощью ручной реализации init(from decoder: Decoder)

struct Response: Decodable {
    
    enum CodingKeys: String, CodingKey {
        case disclaimer
        case license
        case timestamp
        case base
        case rates
    }
    
    var disclaimer: String
    var license: String
    var timestamp: Int
    var base: String
    var rates: [Rate]
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        disclaimer = try container.decode(String.self, forKey: .disclaimer)
        license = try container.decode(String.self, forKey: .license)
        timestamp = try container.decode(Int.self, forKey: .timestamp)
        base = try container.decode(String.self, forKey: .base)
        // ручное преобразование данных
        let ratesDictionary = try container.decode([String : Double].self, forKey: .rates)
        rates = ratesDictionary.map { key, value in Rate(key: key, value: value) }
    }
}

struct Rate: Decodable {
    var key: String
    var value: Double
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.