ios - 在 Swift 中使用 JSON 解码器难以解析 JSON 中的整数值
问题描述
我正在尝试从如下所示的 API 解码一些 JSON(foo 是属性列表的缩写):
{"page":1,"total_results":10000,"total_pages":500,"results":[{"foo":"bar"},{"foo":"bar2"},{"foo":"bar3"}]}
quicktype.io 推荐的结构对我来说也是正确的:
struct ObjectsReturned: Codable {
let page, totalResults, totalPages: Int
let results: [Result]
enum CodingKeys: String, CodingKey {
case page
case totalResults = "total_results"
case totalPages = "total_pages"
case results
}
}
// MARK: - Result
struct Result: Codable {
let foo: String
}
但是,当我尝试解码时,虽然它能够处理页面,但它会在 total_results 上引发错误,如下所示:
typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [_DictionaryCodingKey(stringValue: "total_results", intValue: nil)], debugDescription: "预期解码 Dictionary<String, Any> 但发现一个数字。”,基础错误:无))
此错误的原因可能是什么,我该如何解决?
感谢您的任何建议。
笔记:
解码是通过:
do {
let mything = try JSONDecoder().decode([String:ObjectReturned].self, from: data)
} catch {
print(error)
}
解决方案
您正在尝试解码错误的类型。您的根对象是单个ObjectsReturned
实例,而不是[String:ObjectsReturned]
.
let mything = try JSONDecoder().decode(ObjectsReturned.self, from: json2)
推荐阅读
- sparql - 基本 SPARQL 查询返回三元组,其标签包含 Blazegraph 中的字符串
- rpm - 在 spec 中指定命令卸载 RPM 包
- python - Why is my if statement producing a key error?
- elasticsearch - 在弹性搜索中向现有映射添加默认值
- javascript - 如何嵌套
- 标记值
- machine-learning - 随机森林二次抽样中的选定特征
- python - 有没有更好更快的方法在阈值下从 Scipy 压缩距离矩阵转换为 Scipy 稀疏距离矩阵
- docker - 使用 docker-compose 在 docker 中保护 Redis
- java - chromedriver.exe 和 selenium-chrome-driver.jar 之间的区别
- tfs - 将 TFS 项目存档到硬盘