关键在于如何定义
CodingKeys属性。虽然最常见的情况是
enum它可以是符合
CodingKey协议的任何内容。要创建动态键,可以调用静态函数:
struct Category: Decodable { struct Detail: Decodable { var category: String var trailerPrice: String var isFavorite: Bool? var isWatchlist: Bool? } var name: String var detail: Detail private struct CodingKeys: CodingKey { var intValue: Int? var stringValue: String init?(intValue: Int) { self.intValue = intValue; self.stringValue = "(intValue)" } init?(stringValue: String) { self.stringValue = stringValue } static let name = CodingKeys.make(key: "categoryName") static func make(key: String) -> CodingKeys { return CodingKeys(stringValue: key)! } } init(from prer: Deprer) throws { let container = try prer.container(keyedBy: CodingKeys.self) self.name = try container.depre(String.self, forKey: .name) self.detail = try container.depre([Detail].self, forKey: .make(key: name)).first! }}用法:
let jsonData = """ [ { "categoryName": "Trending", "Trending": [ { "category": "Trending", "trailerPrice": "", "isFavourite": null, "isWatchlist": null } ] }, { "categoryName": "Comedy", "Comedy": [ { "category": "Comedy", "trailerPrice": "", "isFavourite": null, "isWatchlist": null } ] } ]""".data(using: .utf8)!let categories = try! JSonDeprer().depre([Category].self, from: jsonData)(我
isFavourit将JSON 更改为,
isFavourite因为我认为这是拼写错误。如果不是这种情况,则很容易修改代码)



