首页 > 解决方案 > 在 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)
                        }

标签: iosjsonswiftcodablejsondecoder

解决方案


您正在尝试解码错误的类型。您的根对象是单个ObjectsReturned实例,而不是[String:ObjectsReturned].

let mything = try JSONDecoder().decode(ObjectsReturned.self, from: json2)

推荐阅读