我正在尝试从JSON解码我的模型对象(Catalog)的数组,该JSON在序列化相应的“Data”对象后看起来像这样。
{ "id" : 5,
"catalogs" : [ {catalogKeyValue1},{catalogKeyValue2}]
}我的模型对象如下所示
struct Catalog : Codable{
var id : Int
var name : String
var categoryId : Int
var minProductPrice : Int
var maxProductDiscount : Int?
var shareText : String
var collageImage : String
var collageImageAspectRatio : Double?
var shipping : [String : Int]?
var description : String
}我完全理解使用嵌套容器和为目录结构编写自定义初始化器.How可以在不为外部JSOn编写另一个可编码的结构的情况下实现这一点吗
struct CatalogArray: Codable {
var catalogs : [Catalog]
}然后做一些类似这样的事情来获得一个解码的目录数组
let catalogArray = try decoder.decode(CatalogArray.self, from: validData)我的问题是我不需要这个catalogArray结构。有没有办法在不创建不必要的嵌套结构的情况下解码Catalog模型对象。
发布于 2019-02-08 14:02:01
你可以这样做,而不是每次都创建一个新的结构:try container.decode([Catalog].self, forKey: "Catalogs")
Codable类型的数组是自动可编码的。
发布于 2019-02-08 14:51:15
根据您的评论
更多可编码结构的问题是,如果相同的编目数组在另一个响应中具有不同的键,我将需要创建另一个结构。
您可以创建可以为您执行相同操作的泛型结构。下面是一个例子
struct GeneralResponse<T:Codable>: Codable {
let code: Int
let catalogs: T?
enum CodingKeys: String, CodingKey {
case code = "id"
case catalogs = "catalogs"
}
public init(from decoder:Decoder) throws {
let contaienr = try decoder.container(keyedBy: CodingKeys.self)
code = try contaienr.decode(Int.self, forKey: .code)
do {
let object = try contaienr.decodeIfPresent(T.self, forKey: .data)
catalogs = object
} catch {
catalogs = nil
}
}
}现在
您可以将其与不同的目录类型的结构一起使用
喜欢
GeneralResponse<[Catalogs]>或GeneralResponse<[CatalogsAnother]>
希望能对大家有所帮助
https://stackoverflow.com/questions/54586715
复制相似问题