JSONDecoder始终返回“没有与键CodingKeys关联的值". [英] JSONDecoder always returns "No value associated with key CodingKeys"
本文介绍了JSONDecoder始终返回“没有与键CodingKeys关联的值".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下解码结构来解码来自服务器的数据,但它始终返回与键CodingKeys不相关的值".请参见下面的代码
I am using following decoding struct to decode the data from server but it always returns "No value associated with key CodingKeys". Please see the code below
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
The error i am getting is 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
这是来自服务器的完整数据.
This is the full data from server.
{
"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
}
}
推荐答案
具有
let values = try decoder.container(keyedBy: CodingKeys.self)
result = try values.decode(String.self, forKey: .result)
如果数据为零,
解码会使解码失败,请考虑使用decodeIfPresent
或可选的?
足够
decode makes the decoding fails if data is nil consider using decodeIfPresent
or the optional ?
suffices
这篇关于JSONDecoder始终返回“没有与键CodingKeys关联的值".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文