[英]Swift: How to decode result from api which is being returned as a string or as a string of array?
I am using NSUrlConnection and Codable library of Apple. 我正在使用NSUrlConnection和Apple的Codable库。
I am using a web API to signup new users for my application. 我正在使用Web API为我的应用程序注册新用户。 The API returns a status and a message (in json which i map to a model).
API返回状态和消息(在json中,我映射到模型)。
This is my model class: 这是我的模型课:
Struct SignUpResult {
let message: String
let status: String
}
Struct SignUpParams {
let name: String
let email: String
let mobile_no: String
let password: String
}
If the user gave all the parameters correctly then the message is returned as a string. 如果用户正确输入了所有参数,则该消息将以字符串形式返回。 Like this:
像这样:
{
"status": "OK",
"message": "User signup successfully"
}
On the other hand, if the user entered the parameters incorrectly then the message is returned as an array. 另一方面,如果用户输入的参数不正确,则将消息作为数组返回。 Like this:
像这样:
{
"status": "INVALID_PARAMS",
"message": [
"The name may only contain letters."
]
}
If the parameters are incorrect then i get the error 如果参数不正确,那么我会得到错误
"expected to decode a string but found an array instead".
This is the code i get the error on: 这是我得到错误的代码:
let result = JSONDecoder().decode(SignUpResult.self, from: data)
What should i do? 我该怎么办?
My suggestion is to decode status
as enum
and conditionally decode message
as String
or [String]
. 我的建议是将
status
解码为enum
并有条件地将message
解码为String
或[String]
。 messages
is declared as array. messages
被声明为数组。
enum SignUpStatus : String, Decodable {
case success = "OK", failure = "INVALID_PARAMS"
}
struct SignUpResult : Decodable {
let messages : [String]
let status: SignUpStatus
private enum CodingKeys : String, CodingKey { case status, message }
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
status = try container.decode(SignUpStatus.self, forKey: .status)
switch status {
case .success: messages = [try container.decode(String.self, forKey: .message)]
case .failure: messages = try container.decode([String].self, forKey: .message)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.