Ios 如何在Swift 4中编写JSON的可解码代码,其中键是动态的?
我有一个类似这样的JSON 我需要使用Swift 4在我的iOS应用程序中创建相应的可解码结构Ios 如何在Swift 4中编写JSON的可解码代码,其中键是动态的?,ios,json,swift,swift4,decodable,Ios,Json,Swift,Swift4,Decodable,我有一个类似这样的JSON 我需要使用Swift 4在我的iOS应用程序中创建相应的可解码结构 { "cherry": { "filling": "cherries and love", "goodWithIceCream": true, "madeBy": "my grandmother" }, "odd": { "filling": "rocks, I think?", "good
{
"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"
}
}
需要有关制作可解码结构的帮助。如何提及未知键,如
cherry
、odd
和super chocolate
您需要的是在定义编码键时获得创造性。让我们将响应称为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)
}
}
}
// Usage
let list = try! JSONDecoder().decode(FoodList.self, from: jsonData)
您希望在结构中如何准确地表示cherry
、odd
或super chocolate
?您必须基本上使用Swift JSON API吗?还是您也愿意使用类似JSONModel的东西?@AndréSlotta我需要这些标题(cherry,odd,super chocolate)在数组中。@prabodhprakash我应该使用Swift的JSON API。没有本机方法可以做到这一点。库可以帮助你做到这一点。你能告诉我如何用这种方法实现可编码协议吗?不过,我找到了一个网站,解释了json解码和编码的所有内容。但是如何/在何处将foodName与FoodDetail对象关联?@vikzilla问得好。OP不清楚应该如何定义FoodDetail
,所以我错过了名字。见编辑后的答案