How to decode json with unknown key

依然范特西╮ 提交于 2019-12-06 09:18:28

This is done by creating the necessary coding keys for the brand number dynamically, like this:

struct AutoOrderModel: Decodable {
    var brands: BrandList
    let price: [Int]
    let year: [Int]
    let fuelType: [Int]
    let engineCapacity: [String]
    let color: [Int]
    let gearboxId: [Int]
    let isGeorgia: Bool

    enum CodingKeys: String, CodingKey {
        case brands, price, year, color
        case fuelType = "fuel_type"
        case engineCapacity = "engine_capacity"
        case gearboxId = "gearbox_id"
        case isGeorgia = "is_georgia"
    }
}

struct BrandList: Decodable {
    var any: Bool = false
    let brands: [String: Models]

    struct DetailKey: CodingKey {
        var stringValue: String
        var intValue: Int?
        init?(stringValue: String) { 
           self.stringValue = stringValue 
        }
        init?(intValue: Int) { 
            self.stringValue = "\(intValue)"; 
            self.intValue = intValue 
        }
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: DetailKey.self)

        var brands = [String: Models]()
        for key in container.allKeys {
            if let model = try? container.decode(Models.self, forKey: key) {
                brands[key.stringValue] = model
            } else if let any = try? container.decode(Bool.self, forKey: key) {
                self.any = any
            }
        }

        self.brands = brands
    }
}

struct Models: Decodable {
    var isAll: Bool
    var values: [Int]
    var include: Bool

    enum CodingKeys: String, CodingKey {
        case isAll = "is_all"
        case values, include
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!