My JSON:
"Filters": [
{ "filter": "View by",
"products": [
{ "id": 1,
"views": 56700
},
{"id": 2,
"views": 60000
}
]
},
{ "filter": "Ordered by",
"products": [
{ "id": 1,
"orders": 5600
},
{ "id": 2,
"orders": 4300
}
]
}
]
截至目前,以下结构对我有用,但不容易使用
struct Filter: Codable {
let filter: String
let products: [[String: Int]]
}
是否可以仅为产品对象的某些部分创建通用键结构?
简而言之,是否可以仅对"订单"和"视图"应用通用结构,而不对id应用通用结构?
例如:像这样的东西
struct Filter: Codable {
let filter: String
let products: [Product]
}
struct Product: Codable {
let id: Int
let _____: [String: Int] // Some unknown variable
}
你可以写这样的东西:
protocol Product: Codable {
var id: Int {get}
}
struct ProductByView: Product {
let id: Int
let views: Int
}
struct ProductByOrder: Product {
let id: Int
let orders: Int
}
struct Filter: Codable {
let filter: String
let products: [Product]
init(from decoder: Decoder) throws {
//...
}
func encode(to encoder: Encoder) throws {
//...
}
}
但是,实施Filter.init(from:)
或Filter.encode(to:)
会有点复杂。
在您的情况下,您可以使用以下简化的解决方法:
struct Product: Codable {
let id: Int
let views: Int?
let orders: Int?
//... you may need more?
}
struct Filter: Codable {
let filter: String
let products: [Product]
}