【发布时间】:2021-03-25 04:21:56
【问题描述】:
我从不同的 API 收到以下 2 个响应
{
"id": "jdu72bdj",
"userInfo": {
"name": "Sudhanshu",
"age": 28,
"country": "India"
}
}
和
{
"profileId": "jdu72bdj",
"profileDetails": {
"name": "Sudhanshu",
"age": 28,
"country": "India"
}
}
这是在 iOS development 使用 Swift 语言的上下文中。
基本上对象结构相同,但键不同。我正在使用Codable 解析这些,但我想不出一种使用相同结构进行解析的方法。我能想到的就是制作两个这样的不同结构-
public struct Container1: Codable {
public let id: String
public let userInfo: UserProfile?
}
和
public struct Container2: Codable {
public let profileId: String
public let profileDetails: UserProfile?
}
它们都使用通用的UserProfile 结构。
public struct UserProfile: Codable {
public let name: String?
public let age: Int?
public let country: String?
}
有没有办法为两个响应使用一个通用容器结构来解析来自 2 个不同键的响应。我不想要 Container1 和 Container2,因为它们的结构相同。
有什么建议吗?
【问题讨论】:
标签: ios json swift parsing codable