【问题标题】:JSONDecoder always returns "No value associated with key CodingKeys"JSONDecoder 总是返回“No value associated with key CodingKeys”
【发布时间】:2018-12-31 06:02:23
【问题描述】:

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

我得到的错误是解码错误

  ▿ 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
            }
        }

【问题讨论】:

  • 你能从两个结构中删除init并尝试吗??? ,似乎您收到错误而不是有效数据??
  • 结构和代码应该可以工作。您甚至可以删除这两个 init 方法。
  • @vadian - 我试过了。在这种情况下,它不会抛出错误,而是给用户 nil
  • 我在 Playground 中快速测试了给定的 JSON 和代码。它确实有效(有和没有init 方法)。你确定这是完整的 JSON 吗?
  • @vadian 我已经更新了问题请检查

标签: ios swift jsondecoder


【解决方案1】:

拥有

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

如果数据为零,decode 会导致解码失败考虑使用decodeIfPresent 或可选的? 就足够了

【讨论】:

  • 感谢您的回答。如果我使用 decodeIfpresent 那么它不会抛出错误但它会返回 nil user
  • 你确定服务器没有返回 nil / 对解码数据无效吗?你可以打印出来看看
  • @BalajiKondalrayal 可能无关紧要,您可以删除 if letas 吗?用户解码
  • 这节省了我几个小时。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-24
  • 2012-11-13
  • 2014-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-10
相关资源
最近更新 更多