【发布时间】:2018-01-21 19:53:35
【问题描述】:
假设我们有如下 JSON 结构(通常用于 Firebase 的实时数据库):
{
"18348b9b-9a49-4e04-ac35-37e38a8db1e2": {
"isActive": false,
"age": 29,
"company": "BALOOBA"
},
"20aca96e-663a-493c-8e9b-cb7b8272f817": {
"isActive": false,
"age": 39,
"company": "QUONATA"
},
"bd0c389b-2736-481a-9cf0-170600d36b6d": {
"isActive": false,
"age": 35,
"company": "EARTHMARK"
}
}
预期的解决方案:
使用Decodable 我想将其转换为一个包含 3 个元素的数组:
struct BoringEntity: Decodable {
let id: String
let isActive: Bool
let age: Int
let company: String
init(from decoder: Decoder) throws {
// ...
}
}
let entities: [BoringEntity] = try! JSONDecoder()...
id属性对应json对象的根字符串,例如:18348b9b-9a49-4e04-ac35-37e38a8db1e2。
解决方法:
我已经尝试了几种方法,但如果不使用辅助实体(或使用可选项)就无法获得 id 属性:
/// Incomplete BoringEntity version to make Decodable conformance possible.
struct BoringEntityIncomplete: Decodable {
let isActive: Bool
let age: Int
let company: String
}
// Decode to aux struct
let decoded = try! JSONDecoder().decode([String : BoringEntityIncomplete].self, for: jsonData)
// Map aux entities to BoringEntity
let entities = decoded.map { BoringEntity(...) }
使用init(from: Decoder) 并不像其他情况那样简单,因为由于密钥未知,无法使用keyedContainer(,)。
Decodable 不适合这类情况吗?
【问题讨论】:
标签: json swift4 codable decodable