我有如下所示的JSON:
{
success: true,
message: null,
messages: null,
data: [
[ ... ]
]
}
现在我想知道,我可以通过以下方式解决此问题:
struct Something: Codable {
let data: [[Data]]
}
something.data.flatMap { $0 }
但是我宁愿这样做:
struct Something: Codable {
let data: [Data]
}
我已经知道我可以使用CodingKeys
枚举和container.nestedContainer(...)
集合通过JSON实现导航,但是当没有键,而只有数组中的数组时,如何实现此功能?我可以使用Decodable
上的自定义init来实现吗?如果可以,如何实现?
答案 0 :(得分:0)
一种可能的解决方案是编写一个自定义的初始化程序来展平数组
struct Root : Decodable {
let success : Bool
let data : [Foo]
private enum CodingKeys : String, CodingKey { case success, data }
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
success = try container.decode(Bool.self, forKey: .success)
let arrayData = try container.decode([[Foo]].self, forKey: .data)
guard !arrayData.isEmpty else { throw DecodingError.dataCorruptedError(forKey: .data, in: container, debugDescription: "Object is empty") }
data = arrayData.first!
}
}
struct Foo : Decodable { ... }
基金会框架中存在类型Data
。强烈建议您不要将其用作自定义类型。