'Different keys in json objects
I have json response like this and server returns different keys for "tiered_prices"
"tiered_prices": {
"100": "23500",
"200": "23300"
}
"tiered_prices": {
"500": "23500",
"1000": "23300"
}
When tiered prices values were only "100" and "200" I decoded json response like this.
struct TieredPriceResponse: Decodable {
let tiered_prices: TieredPrices }
struct TieredPrices: Decodable {
let firstPrice: String
let secondPrice: String
enum CodingKeys: String, CodingKey {
case firstPrice = "500"
case secondPrice = "1000"
}
}
How properly decode such json objects, where keys will always be different? I tried this answer Swift json dynamic key parsing for json but got error
struct TieredPriceResponse: Decodable {
let tiered_prices: TieredPrices
}
struct TieredPrices: Decodable {
var firstPrice: String = ""
enum CodingKeys: String, CodingKey, CaseIterable {
case firstPrice = "200"
case tPrice1 = "100"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let precisionValue = try container.decodeIfPresent(String.self, forKey: .firstPrice) {
firstPrice = precisionValue
}
if let precisionValue = try container.decodeIfPresent(String.self, forKey: .tPrice1) {
firstPrice = precisionValue
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
