【发布时间】:2023-02-09 08:38:34
【问题描述】:
Codable 结构创建,根据响应解码,响应上的一些键。但是 api 响应发送的密钥决定了在父 json 中使用的模型。如何在内部访问它:下面的演示代码..
如果值为“First”,那么我想使用 BodyResponse1,在所有其他情况下使用 BodyResponse2
public protocol BodyResponse: Codable { }
struct BodyResponse1: BodyResponse {
let title_1: String
let description_1: String
}
struct BodyResponse2: BodyResponse {
let title_2: String
let description_2: String
}
struct BaseModel {
let key: String
let child_model: ChildModel?
}
struct ChildModel {
let body: BodyResponse?
enum CodingKeys: String, CodingKey {
case body
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let value = "" // access the value for key in base model: how
if value == "First" {
body = try? BodyResponse1.init(from: container.superDecoder(forKey: .body))
} else {
body = try? BodyResponse2.init(from: container.superDecoder(forKey: .body))
}
}
}
示例 json:
{
"key": "First",
"child_model": {
"body": {
"title_1": "",
"description_1": ""
},
"random_key": 12
}
}
{
"key": "Second",
"child_model": {
"body": {
"title_2": "",
"description_2": ""
},
"random_key": 12
}
}
【问题讨论】:
-
您知道所有可以归还的钥匙吗?或者它也是动态的?
-
body 内的键将有 body1 或 body2