如何在Swift 4中编写一个可解码的JSON,其中密钥是dynamic的?

我有这样的JSON。

我需要使用Swift 4在我的iOS应用程序中创build相应的Decodable结构。

{ "cherry": { "filling": "cherries and love", "goodWithIceCream": true, "madeBy": "my grandmother" }, "odd": { "filling": "rocks, I think?", "goodWithIceCream": false, "madeBy": "a child, maybe?" }, "super-chocolate": { "flavor": "german chocolate with chocolate shavings", "forABirthday": false, "madeBy": "the charming bakery up the street" } } 

在制作Decodable Struct时需要帮助。 如何提到像cherryoddsuper-chocolate的未知键。

你需要的是定义CodingKeys创意。 让我们调用响应一个FoodList和内部结构FoodDetail 。 你还没有定义FoodDetail的属性,所以我认为这些键都是可选的。

 struct FoodDetail: Decodable { var filing: String? var goodwWithIceCream: Bool? var madeBy: String? var flavor: String? var forABirthday: Bool? } struct FoodList: Decodable { var foodNames: [String] var foodDetails: [FoodDetail] // This is a dummy struct as we only use it to satisfy the container(keyedBy: ) function private struct CodingKeys: CodingKey { var intValue: Int? var stringValue: String init?(intValue: Int) { self.intValue = intValue; self.stringValue = "" } init?(stringValue: String) { self.stringValue = stringValue } } init(from decoder: Decoder) throws { self.foodNames = [String]() self.foodDetails = [FoodDetail]() let container = try decoder.container(keyedBy: CodingKeys.self) for key in container.allKeys { self.foodNames.append(key.stringValue) try self.foodDetails.append(container.decode(FoodDetail.self, forKey: key)) } } } // Usage let list = try! JSONDecoder().decode(FoodList.self, from: jsonData) 
Interesting Posts