【发布时间】:2020-07-28 13:59:51
【问题描述】:
我正在尝试从如下所示的 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.DecodingError.Context(编码路径: [_DictionaryCodingKey(stringValue: "total_results", intValue: nil)], debugDescription: "预期解码 Dictionary 但是 而是找到了一个数字。”,基础错误:无))
此错误的原因可能是什么?我该如何解决?
感谢您的任何建议。
注意:
解码是通过:
do {
let mything = try JSONDecoder().decode([String:ObjectReturned].self, from: data)
} catch {
print(error)
}
【问题讨论】:
-
那是正确的 json 吗?如果是,您应该将
decode称为decode(ObjectReturned.self, from: data)
标签: ios json swift codable jsondecoder