更新时间:2021-12-20 00:23:21
您只需要自己实现 init(from:)
并尝试解码 subscription
的值键既作为表示 Subs
的 Dictionary
,又作为 String
的键.
You simply need to implement init(from:)
yourself and try decoding the value for the subscription
key both as a Dictionary
representing Subs
and as a String
.
struct OrderLine: Codable {
let absUrl: String?
let restApiUrl : String?
let description : String?
let quantity : Int?
let subscription: Subs?
let total: Double?
private enum CodingKeys: String, CodingKey {
case absUrl, restApiUrl, description, quantity, subscription, total
}
init(from decoder:Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.absUrl = try container.decodeIfPresent(String.self, forKey: .absUrl)
self.restApiUrl = try container.decodeIfPresent(String.self, forKey: .restApiUrl)
self.description = try container.decodeIfPresent(String.self, forKey: .description)
self.quantity = try container.decodeIfPresent(Int.self, forKey: .quantity)
self.total = try container.decodeIfPresent(Double.self, forKey: .total)
if (try? container.decodeIfPresent(String.self, forKey: .subscription)) == nil {
self.subscription = try container.decodeIfPresent(Subs.self, forKey: .subscription)
} else {
self.subscription = nil
}
}
}