JSONDecoder始终返回“没有与键CodingKeys关联的值”

时间:2018-07-23 17:52:54

标签: ios swift jsondecoder

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

1 个答案:

答案 0 :(得分:2)

拥有

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

如果数据为零,则解码会使解码失败,请考虑使用decodeIfPresent或可选的?