我正在为 IOS Swift UI 开发一个现有的 Android Kotlin 应用。
在 Kotlin 中使用 Gson 时,我有一个 Client 模型类:
abstract class Client(
@SerializedName("nombre")
var name: String? = null,
@SerializedName(value="cliente_id", alternate = ["id"])
var client_id: Int = -1,
)
如您所见,我使用 @SerializedName()
为 Client 属性 name
或 client_id
提供更改名称。我这样做是因为当我从 API 获取数据时,客户端 Json 具有“nombre”而不是我想要的“name”。因此,@SerializedName() 可以将 JSON 中的“nombre”检测为“name”,或将 Kotlin 模型类中的“cliente_id”检测为“client_id”。这样我就可以使用我自己的属性名称从 API 读取数据。
好吧,现在我在 Swift 中面临同样的问题。我想使用我自己的属性名称,而不是 API JSON 属性名称。
我的 swift Client 模型类如下所示:
class Client: Identifiable, Decodable{
init(id: Int, token: String) {
self.cliente_id = id
self.token = token
}
let cliente_id: Int
let token: String
}
我从 API 获取客户端数据,如下所示:
let request = AF.request(
url, method: .post,
parameters: parameters,
encoder: JSONParameterEncoder.default
)
request.validate(statusCode: 200...299)
request.responseDecodable(of: Client.self) { response in
if let loginResponse = response.value{//Success
loginPublisher.send(loginResponse)
}
else{//Failure
loginPublisher.send(completion: Subscribers.Completion<NetworkError>.failure(.thingsJustHappen))
}
}
为了能够使用 Client
可解码的内容,Client
必须实现 Decodable
。好吧,我想要的只是 Client 将 id
而不是 cliente_id
作为属性名称。
类似于
class Client: Identifiable, Decodable{
init(id: Int, token: String) {
self.id = id
self.token = token
}
@NameforDecode("cliente_id")
let id: Int
let token: String
}
这可能吗?
最佳答案
在 Swift 中,您可以通过为类型提供自定义 CodingKeys
来实现此目的:
extension Client: Decodable {
enum CodingKeys: String, CodingKey {
case id = "cliente_id"
case token
}
}
枚举案例必须与您的属性相对应;如果 JSON 中的键与您的属性名称不匹配,则可以将原始值声明为 String
。 Encoding and Decoding Custom Types中有更多信息开发者文章。
关于swift - 为 Decodable 类中的属性设置更改名称 | swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69015207/