如何为稍微不同的json示例创建一个通用的可编码结构,responses.For示例response A和B具有几乎相同的属性,而B有一些额外的属性,称为Designation.Is,可以为此场景创建通用可编码结构吗?
//Response A
{
"name" : "Jhon",
"age" : 23,
"mobile" : "+11012341234",
.
.
.
}
//Response B
{
"name" : "Jhon",
"age" : 23,
"mobile" : "+11012341234",
.
.
.
"designation": "Manager"
}发布于 2022-02-12 03:58:34
您可以使用这样的选项:
struct Response: Decodable {
var name: String
var age: Int
var mobile: String
var designation: String?
// If you need to decode, it would look like this:
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
age = try container.decode(Int.self, forKey: .age)
mobile = try container.decode(String.self, forKey: .mobile)
// Decode designation if provided
if container.contains(.designation){
designation = try container.decode(String.self, forKey: .designation)
}
}
}https://stackoverflow.com/questions/71088877
复制相似问题