gpt4 book ai didi

ios - JSONDecoder 总是返回 "No value associated with key CodingKeys"

转载 作者:搜寻专家 更新时间:2023-11-01 06:59:34 25 4
gpt4 key购买 nike

我正在使用以下解码结构来解码来自服务器的数据,但它总是返回“没有与键 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
}
}

最佳答案

拥有

 let values = try decoder.container(keyedBy: CodingKeys.self)
result = try values.decode(String.self, forKey: .result)

decode 如果数据为 nil 则解码失败考虑使用 decodeIfPresent 或可选的 ? 就足够了

关于ios - JSONDecoder 总是返回 "No value associated with key CodingKeys",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51484654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com