json - 当键根据用户输入更改时如何从 json 解码变量?

标签 json swift swift4 codable jsondecoder

我正在尝试解析来自 CoinmarketCap 的一些 JSON 响应在 Swift 4 中使用 JSONDecoder()。但问题是来自 json 的响应会根据用户输入而变化。例如,如果用户想要欧元价格,输出如下:

[
    {
        "price_eur": "9022.9695444"
    }
]

但是如果用户想要以英镑为单位的价格:

[
    {
        "price_gbp": "7906.8032145"
    }
]

所以问题是,如果变量(json 键)名称发生变化,我应该如何制作从 Decodable 继承的结构?

最佳答案

您可以通过为您的结构创建自定义 init(from:) 方法来解码动态 key ,然后使用两组编码 key ,一个包含所有 key 的 enum是在编译时已知的,另一个 struct 使用用户输入生成的动态键初始化(包含货币名称)。

在您的自定义 init(from:) 方法中,您只需要使用各自的键解码每个属性。

let chosenCurrency = "gbp"

struct CurrencyResponse: Decodable {
    let name:String
    let symbol:String
    let price:String
    private static var priceKey:String {
        return "price_\(chosenCurrency)"
    }

    private enum SimpleCodingKeys: String, CodingKey {
        case name, symbol
    }

    private struct PriceCodingKey : CodingKey {
        var stringValue: String
        init?(stringValue: String) {
            self.stringValue = stringValue
        }
        var intValue: Int?
        init?(intValue: Int) {
            return nil
        }
    }

    init(from decoder:Decoder) throws {
        let values = try decoder.container(keyedBy: SimpleCodingKeys.self)
        name = try values.decode(String.self, forKey: .name)
        symbol = try values.decode(String.self, forKey: .symbol)
        let priceValue = try decoder.container(keyedBy: PriceCodingKey.self)
        price = try priceValue.decode(String.self, forKey: PriceCodingKey(stringValue:CurrencyResponse.priceKey)!)
    }
}

do {
    let cryptoCurrencies = try JSONDecoder().decode([CurrencyResponse].self, from: priceJSON.data(using: .utf8)!)
} catch {
    print(error)
}

测试 JSON:

let priceJSON = """
    [
    {
    "id": "bitcoin",
    "name": "Bitcoin",
    "symbol": "BTC",
    "rank": "1",
    "price_\(chosenCurrency)": "573.137",
    "price_btc": "1.0",
    "24h_volume_\(chosenCurrency)": "72855700.0",
    "market_cap_\(chosenCurrency)": "9080883500.0",
    "available_supply": "15844176.0",
    "total_supply": "15844176.0",
    "percent_change_1h": "0.04",
    "percent_change_24h": "-0.3",
    "percent_change_7d": "-0.57",
    "last_updated": "1472762067"
    },
    {
    "id": "ethereum",
    "name": "Ethereum",
    "symbol": "ETH",
    "rank": "2",
    "price_\(chosenCurrency)": "12.1844",
    "price_btc": "0.021262",
    "24h_volume_\(chosenCurrency)": "24085900.0",
    "market_cap_\(chosenCurrency)": "1018098455.0",
    "available_supply": "83557537.0",
    "total_supply": "83557537.0",
    "percent_change_1h": "-0.58",
    "percent_change_24h": "6.34",
    "percent_change_7d": "8.59",
    "last_updated": "1472762062"
}
]
"""

关于json - 当键根据用户输入更改时如何从 json 解码变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48422653/

相关文章:

swift - 试图找到 Swift MIDI 回调解决方法

swift - 在 Swift 4 中递归解析数组

jquery - 使用 jQuery 解析不带引号的 JSON 数据

ios - 子类 UIPickerView swift

python - 使用Python访问JSON文件,得到 "Memory Error"

ios - 使用未解析的标识符 'AVAsset'

swift - 如何刷新 TableView 中的特定单元格并存储更改的数据以便稍后在同一 TableView 中显示

swift - `RLMArray` 不符合协议(protocol) 'Encodable'

php - json_decode() 返回错误 "Notice: Trying to get property of non-object"

java - 日期的 JSON 序列化策略