如何在Swift 4中为JSON编写一个Decodable,其中键是动态的? [英] How to write a Decodable for a JSON in Swift 4, where keys are dynamic?
本文介绍了如何在Swift 4中为JSON编写一个Decodable,其中键是动态的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是这样的JSON。
I've a JSON like this.
我需要使用Swift 4在我的iOS应用中制作相应的Decodable结构。
I need to make a corresponding Decodable struct in my iOS app using Swift 4.
{
"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
,奇数
和超巧克力
。
Need help on making the Decodable Struct. How to mention the unknown keys like cherry
,odd
and super-chocolate
.
推荐答案
您需要的是创造性地定义 CodingKeys
。让我们将响应称为 FoodList
,内部结构 FoodDetail
。你还没有定义 FoodDetail
的属性,所以我认为这些键都是可选的。
What you need is to get creative in defining the CodingKeys
. Let's call the response a FoodList
and the inner structure FoodDetail
. You haven't defined the properties of FoodDetail
so I assume that the keys are all optional.
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)
这篇关于如何在Swift 4中为JSON编写一个Decodable,其中键是动态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文