ios - 没有与键 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") 关联的值。编码路径:[]
解决方案
推荐阅读
- hadoop - 更改区域数时的 Hbase 行键加盐
- bcpl - 如何在 MacOS 或 Linux 下运行 BCPL
- sql-server - 部署期间的 SSRS 死锁
- sql-server - 嵌套在自身 SQL 服务器上的联接
- python - Read the keys and values from the columns of a dataframe in Python
- javascript - Next.js 构建版本失败,“无法读取未定义的属性 'auth'”
- javascript - 图片未显示在浏览器中
- c# - Cefsharp - 键盘在重新聚焦之前无法工作
- java - 大型 json 文件上的 Talend Java 堆空间
- terraform - 如何将多个 aws 提供程序传递给一个模块?