Handling incrementing JSON name using Swift

后端 未结 2 1590
既然无缘
既然无缘 2021-01-17 03:05

I have a JSON object with incrementing names to parse and I want to store the output into an object with a name field and a list of pet field. I normally use JSONDecoder as

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-17 03:22

    Codable has provisions for dynamic keys. If you absolutely can't change the structure of the JSON you're getting, you could implement a decoder for it like this:

    struct VetShop: Decodable {
        let shopName: String
        let pets: [String]
    
        struct VetKeys: 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: VetKeys.self)
            var pets = [String]()
            var shopName = ""
            for key in container.allKeys {
                let str = try container.decode(String.self, forKey: key)
                if key.stringValue.hasPrefix("pet") {
                    pets.append(str)
                } else {
                    shopName = str
                }
            }
            self.shopName = shopName
            self.pets = pets
        }
    }
    

提交回复
热议问题