【发布时间】:2020-12-17 09:43:26
【问题描述】:
我有一个基本模型 -
struct BaseModel<T:Decodable>: Decodable {
let jsonData: [T]?
let status: Bool?
let message: String?
enum CodingKeys: String, CodingKey {
case jsonData = "data"
case status = "success"
case message
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
do {
if let string = try container.decodeIfPresent(T.self, forKey: .jsonData) {
print(string)
jsonData = [string]
} else {
jsonData = nil
}
} catch DecodingError.typeMismatch {
jsonData = try container.decodeIfPresent([T].self, forKey: .jsonData)
}
status = try container.decodeIfPresent(Bool.self, forKey: .status)
message = try container.decodeIfPresent(String.self, forKey: .message)
}
}
我在 jsonData 下得到两种类型的响应
- 对象
- 数组
如果我收到作为对象的响应,则在解码时出错。如果我选择 let jsonData: T?,则在解码 Array 响应时遇到问题。
我在我的网络模型中使用这个模型。看起来像-
func performOperation<T:Decodable>(urlEndPoint: String, method: HTTPMethod, param: Parameters?, isJsonAvailable: Bool, completion: @escaping(_ response: T?, [T]?, String?, Bool?) ->Void) {
AF.request(urlEndPoint, method: method, parameters: param, headers: header).validate(statusCode: 200..<500).responseDecodable(of: BaseModel<T>.self, decoder: decoder) { (response) in
}
Object情况下的Json响应-
{
"success": true,
"data": {
"heading": "Same text 1",
"title": "Sample Text 2",
"content": "Sample text 3"
},
"message": "Api response received"
}
ArrayList情况下的Json响应-
{
"success": true,
"data": [
{
"id": 1,
"name": "Home"
},
{
"id": 2,
"name": "Profile"
}
],
"message": "Menu List"
}
【问题讨论】:
-
显示您的
Object和您的Array类型。同时显示您的 JSON 响应。 -
另外请发布您从
JSONDecode收到的错误。 -
@gcharita,好像在使用我自己的上述代码????感谢您一直以来的支持。非常感谢,如果我遇到任何问题会告诉你。
标签: swift alamofire codable decodable