サーバーからのデータをデコードするために次のデコード構造体を使用していますが、常に「キー CodingKeys に関連付けられた値がありません」を返します。以下のコードをご覧ください
struct UserDecode: Codable {
var user: User?
var result: String?
private enum CodingKeys: String, CodingKey {
case user = "Records"
case result = "Result"
}
init(from decoder: Decoder) throws {
do {
let values = try decoder.container(keyedBy: CodingKeys.self)
result = try values.decode(String.self, forKey: .result)
user = try values.decode(User.self, forKey: .user)
} catch {
print(error.localizedDescription)
}
}
}
struct User: Codable {
var mobile: Int?
var userId: Int?
var name: String?
private enum CodingKeys: String, CodingKey {
case userId = "MEMBERID"
case name = "Membername"
case mobile = "Mobile"
}
init(from decoder: Decoder) throws {
do {
let values = try decoder.container(keyedBy: CodingKeys.self)
userId = try values.decode(Int.self, forKey: .userId)
name = try values.decode(String.self, forKey: .name)
mobile = try values.decode(Int.self, forKey: .mobile)
}
catch {
print(error.localizedDescription)
}
}
}
サーバーからの応答は
{
"Result": "OK",
"Records": {
"MEMBERID": 1,
"Membername": "Balaji",
"Mobile": 12345678901,
}
}
私が得ているエラーはDecodingErrorです
▿ keyNotFound : 2 elements
- .0 : UserCodingKeys(stringValue: "Result", intValue: nil)
▿ .1 : Context
- codingPath : 0 elements
- debugDescription : "No value associated with key UserCodingKeys(stringValue: \"Result\", intValue: nil) (\"Result\")."
- underlyingError : nil
これはサーバーからの完全なデータです。
{
"Result": "OK",
"Records": {
"MEMBERID": 1,
"Membername": "Balaji",
"Mobile": 12345678901,
"PAYLEVEL": 0,
"UserName": "12345678901",
"Token": "SroRn65YfqLSGcMMHaFsl2c5RGEiv1JcHHPnpFXa7quKOPIRsqUEhpcWpGKl_23O4PJcgmLiFb9T8TAq1fgyftgpffJKCbJUozYjKF68dvChrb8Qv1egw_paxnUZlYBzwlfXUtFQ23Y1Wu6UBZHdycY4PwS9a1f_e1zG_etiV9R-E8kOLMoqwQTXTtRZ3NPEXsHDtS3KRz471c9Bzbx_v3FGw4HDcvGgejWaC1Zo6nHE8IQ7MG2oX5KuneZTqd1X",
"Imageurl": "https://.net/images/abc.png",
"WalletBalance": 0,
"ResponseCode": 1,
"ResponseMessage": "LOGIN SUCCESS",
"ImageType": "1.jpeg",
"Emailid": "ab.net",
"FirstOrder": 1,
"FirstOrderImage": "https:.net/images/abc.png"
}
}
デコーダーコード:
let task = session.dataTask(with: request) {(data, response, error) in
let (success, errorMessage) = self.isValidResponse(error: error, data: data, response: response as? HTTPURLResponse)
if !success {
completionHandler(nil, errorMessage)
return
}
// Parse the data
do {
let decoder = JSONDecoder()
if let userResult = try decoder.decode(UserDecode.self, from: data!) as? UserDecode {
completionHandler(userResult.user, nil)
return
}
else {
completionHandler(nil, ErrorMessage.unableToProcess)
return
}
} catch {
print("Could not parse JSON data")
completionHandler(nil, ErrorMessage.unableToProcess)
return
}
}