【发布时间】:2018-10-30 02:30:49
【问题描述】:
我已阅读 How to decode a nested JSON struct with Swift Decodable protocol? 它没有解决我将字符串文字数值用作根字典的特定用例。
还有How to decode a nested JSON struct with Swift Decodable protocol? Imanou Petit 的回答。 Can't decode JSON data from API Leo Dabus 的回答。
货币本身就是由 data 字典中的字符串数字表示的字典,所以这让我很反感。我正在寻找使用枚举的最 Swifty 4 模型,可以很容易地看到哪些容器对应于哪些字典。
附言大卫贝瑞给出了一个很好的答案,我已经在下面实现了。如果其他人有其他方法来获得相同的结果,我很乐意看到不同的建议。也许有一些新的 Swift 4 方法还不为人所知或其他设计模式。
代码
struct RawServerResponse {
enum RootKeys: String, CodingKey {
case data
case btc = "1"
case eth = "1027"
case iota = "1720"
case ripple = "52"
case neo = "1376"
case quotes
case USD
}
enum BaseKeys: String, CodingKey {
case id, name, symbol, maxSupply = "max_supply"
}
enum QuotesKeys: String, CodingKey {
case USD
}
enum USDKeys: String, CodingKey {
case price, marketCap = "market_cap"
}
let data: String
let id: Int
let name: String
let symbol: String
let maxSupply: Double
let price: Double
let marketCap: Double
}
extension RawServerResponse: Decodable {
init(from decoder: Decoder) throws {
// data
let container = try decoder.container(keyedBy: RootKeys.self)
data = try container.decode(String.self, forKey: .data)
// id
let idContainer = try container.nestedContainer(keyedBy: BaseKeys.self, forKey: .data)
id = try idContainer.decode(Int.self, forKey: .id)
// price
let priceContainer = try container.nestedContainer(keyedBy: USDKeys.self, forKey: .USD)
price = try priceContainer.decode(Double.self, forKey: .price)
}
}
API / JSON https://api.coinmarketcap.com/v2/ticker/
{
"data": {
"1": {
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"website_slug": "bitcoin",
"rank": 1,
"circulating_supply": 17041575.0,
"total_supply": 17041575.0,
"max_supply": 21000000.0,
"quotes": {
"USD": {
"price": 8214.7,
"volume_24h": 5473430000.0,
"market_cap": 139991426153.0,
"percent_change_1h": 0.09,
"percent_change_24h": 2.29,
"percent_change_7d": -2.44
}
},
"last_updated": 1526699671
},
"1027": {
"id": 1027,
"name": "Ethereum",
"symbol": "ETH",
"website_slug": "ethereum",
"rank": 2,
"circulating_supply": 99524121.0,
"total_supply": 99524121.0,
"max_supply": null,
"quotes": {
"USD": {
"price": 689.891,
"volume_24h": 2166100000.0,
"market_cap": 68660795252.0,
"percent_change_1h": 0.13,
"percent_change_24h": 2.51,
"percent_change_7d": 2.54
}
},
"last_updated": 1526699662
}
}
【问题讨论】: