[英]Swift Codable: Decoding dynamic keys
我正在嘗試練習 Swift 的 Codable API。 我發送一個網絡請求,每次收到一行,我必須處理動態密鑰:
響應示例 1:
{
"EUR": 4695.01
}
響應示例 2:
{
"USD": 479.01
}
響應示例 3:
{
"BTC": 4735.01
}
我嘗試了這種方法來解析動態鍵:
struct ConversionResponseModel: Decodable {
typealias destinationCurrency = String
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
}
}
和我的獲取請求:
do {
let myResult = try JSONDecoder().decode(ConversionResponseModel.self, from: data)
print(myResult)
} catch {
print(error)
}
但我得到了這個結果: ConversionResponseModel()
,但不是貨幣值。 聽起來我好像錯過了什么。 請提供任何幫助。 謝謝
您快到了。 您獲得的 JSON 將返回[String:Double]
的字典。 然后,您可以使用以下方法隱藏它:
struct ConversionResponseModel: Decodable {
typealias DestinationCurrency = String
let currency : DestinationCurrency
let value : Double
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let dict = try container.decode([String:Double].self)
guard let key = dict.keys.first else {
throw NSError(domain: "Decoder", code: 0, userInfo: [:])
}
currency = key
value = dict[key] ?? -1
}
}
注意:考慮到 Rob Napier 的評論,您可以將Decimal
替換為Double
- 有關更多詳細信息,請參閱他對原始問題的評論
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.