为稍微不同的json响应创建通用的可编码文件-Swift



如何在swift中为略有不同的json响应创建一个通用的可编码结构。例如,response AB有几乎相同的属性,而B有一些额外的属性,称为Designation。有可能为这种场景创建通用的可编码结构吗?

//Response A
{
"name" : "Jhon",
"age" : 23,
"mobile" : "+11012341234",
.
.
.
}
//Response B
{
"name" : "Jhon",
"age" : 23,
"mobile" : "+11012341234",
.
.
.
"designation": "Manager"
}

您可以使用这样的选项:

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)
}
}
}

相关内容

  • 没有找到相关文章

最新更新