我需要使用Swift 4在我的iOS应用程序中创建相应的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" }}
需要有关制作可解码结构的帮助.如何提及樱桃,奇数和超巧克力等未知密钥.
解决方法 您需要的是在定义CodingKeys时发挥创意.让我们将响应称为FoodList和内部结构FoodDetail.您尚未定义FoodDetail的属性,因此我假设这些键都是可选的.struct FoodDetail: Decodable { var name: String! var filling: String? var gooDWithIceCream: Bool? var madeBy: String? var flavor: String? var forABirthday: Bool? enum CodingKeys: String,CodingKey { case filling,gooDWithIceCream,madeBy,flavor,forABirthday }}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 { let foodname = key.stringValue var foodDetail = try container.decode(FoodDetail.self,forKey: key) foodDetail.name = foodname self.foodnames.append(foodname) self.foodDetails.append(foodDetail) } }}// Usagelet List = try! JsONDecoder().decode(FoodList.self,from: JsonData)总结
以上是内存溢出为你收集整理的ios – 如何在Swift 4中为JSON编写一个Decodable,其中键是动态的?全部内容,希望文章能够帮你解决ios – 如何在Swift 4中为JSON编写一个Decodable,其中键是动态的?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)