首页 > 解决方案 > 没有与键 CodingKeys 关联的值 - JSONDecoder 错误

问题描述

我的Session模型看起来像这样

public struct Session: Codable {
    let name: String
    
    let key: String
    
    let subscriber: Int
}

我想用 Alamofire 的responseData方法调用 API 并将接收到的数据解码为Session对象,但是每次解码都失败。

Alamofire.request(url, method: .post).responseData { response in
                    if let error = response.error {
                        failure?(error)
                    } else if let data = response.result.value {
                        do {
                            if let str = String(data: data, encoding: .utf8) {
                                // This prints out a correct JSON string
                                print(str)
                            }
                            let session = try JSONDecoder().decode(Session.self, from: data)
                            success(session.key)
                        } catch let DecodingError.keyNotFound(key, context) {
                            print("Key '\(key)' not found:", context.debugDescription)
                            print("codingPath:", context.codingPath)
                        } catch {
                            print(error.localizedDescription)
                        }
                    }
                }

我在解码之前将 Data 的内容打印到控制台,它看起来像一个有效的 JSON,而且我的模型中没有任何拼写错误。解码失败的原因可能是什么?

控制台输出:

{"session":{"subscriber":0,"name":"someuser","key":"somekey"}}

未找到键 'CodingKeys(stringValue: "name", intValue: nil)':没有与键 CodingKeys(stringValue: "name", intValue: nil) ("name") 关联的值。编码路径:[]

标签: iosjsonswiftcodable

解决方案


推荐阅读