Swift 4 parsing json numeric keys with 1+n amount

后端 未结 1 1991
孤街浪徒
孤街浪徒 2021-01-15 04:36

I still learning this Codable/Decodable new in Swift 4 for JSON parsing.

I am able to build a struct and grab the temperature keys but the Pump and othe

相关标签:
1条回答
  • 2021-01-15 05:28

    The value for key circuit is a dictionary.

    If you need fast access by number decode the object as [String:Circuit]

    public struct ServerReponse: Codable {
       let temperature: Temperature
       let circuit: [String:Circuit] 
    }
    

    If an array is more suitable write a custom initializer which additionally maps the values to an array.

    public struct ServerReponse: Codable {
        let temperature: Temperature
        let circuits: [Circuit]
    
        private enum CodingKeys: String, CodingKey { case temperature, circuits = "circuit"}
    
        public init(from decoder: Decoder) throws {
            let container = try decoder.container(keyedBy: CodingKeys.self)
            temperature = try container.decode(Temperature.self, forKey: .temperature)
            let circuitData = try container.decode([String:Circuit].self, forKey: .circuits)
            circuits = Array(circuitData.values).sorted(by: {$0.number < $1.number})
        }
    }
    
    0 讨论(0)
提交回复
热议问题