基础实体:
struct BoringEntity: Decodable { let id: String let isActive: Bool let age: Int let company: String}
解决方案1:使用没有密钥的额外结构
/// Incomplete BoringEntity version to make Decodable conformance possible.private struct BoringEntityBare: Decodable { let isActive: Bool let age: Int let company: String}// Depre to aux structprivate let depred = try! JSonDeprer().depre([String : BoringEntityBare].self, from: jsonData)// Map aux entities to BoringEntitylet entities = depred.map { BoringEntity(id:PhantomKeys.key, isActive:struct BoringEntities: Decodable { var entities = [BoringEntity]() // This really is just a stand-in to make the compiler happy. // It doesn't actually do anything. private struct PhantomKeys: CodingKey { var intValue: Int? var stringValue: String init?(intValue: Int) { self.intValue = intValue; self.stringValue = "(intValue)" } init?(stringValue: String) { self.stringValue = stringValue } } private enum BareKeys: String, CodingKey { case isActive, age, company } init(from deprer: Deprer) throws { let container = try deprer.container(keyedBy: PhantomKeys.self) // There's only one key for key in container.allKeys { let aux = try container.nestedContainer(keyedBy: BareKeys.self, forKey: key) let age = try aux.depre(Int.self, forKey: .age) let company = try aux.depre(String.self, forKey: .company) let isActive = try aux.depre(Bool.self, forKey: .isActive) let entity = BoringEntity(id: key.stringValue, isActive: isActive, age: age, company: company) entities.append(entity) } }}let entities = try JSonDeprer().depre(BoringEntities.self, from: jsonData).entitiesprint(entities).value.isActive, age: .value.age, company: .value.company) }print(entities)
解决方案2:使用包装器
多亏了Code Different,我得以将自己的方法与他的想法结合起来,但是却无法解决:必须始终使用额外的实体。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)