Ios 在Swift中使用JSON解码器很难解析JSON中的整数值

Ios 在Swift中使用JSON解码器很难解析JSON中的整数值,ios,json,swift,codable,jsondecoder,Ios,Json,Swift,Codable,Jsondecoder,我试图从一个API中解码一些JSON,如下所示(foo是属性列表的缩写): quicktype.io推荐的结构在我看来也是正确的: struct ObjectsReturned: Codable { let page, totalResults, totalPages: Int let results: [Result] enum CodingKeys: String, CodingKey { case page case totalRe

我试图从一个API中解码一些JSON,如下所示(foo是属性列表的缩写):

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_结果上抛出一个错误,如下所示:

类型不匹配(Swift.Dictionary, Swift.DecodingError.Context(编码路径: [[u DictionaryCodingKey(stringValue:“总计结果”,intValue:nil)], debugDescription:“应解码字典,但 改为找到了一个数字。“,underyingerror:nil))

此错误的原因可能是什么?我如何修复它

谢谢你的建议

注:

解码是通过:

do {
                            let mything = try JSONDecoder().decode([String:ObjectReturned].self, from: data)
                        } catch {
                            print(error)
                        }

您试图解码错误的类型。您的根对象是单个
objectsreentern
实例,而不是
[String:objectsreentern]

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

错误本身很明显,它表示您正在尝试解码
字典
,但
JSONDecoder
找不到。您可能是从其他地方复制了此代码,这可能就是犯此错误的原因。你只要看一看就应该能够找出模型。在这里,您可以看到开头没有一个键的值是预期的
ObjectReturned
。如果
JSON
已经:

{"someStringKey":{"page":1,"total_results":10000,"total_pages":500,"results":[{"foo":"bar"},{"foo":"bar2"},{"foo":"bar3"}]}}
你的解码应该是有效的。相反,在您的示例中,
JSON
没有前导键,如上面的示例
“someStringKey”
所示,因此您只需要:

do {
    let mything = try JSONDecoder().decode(ObjectsReturned.self, from: data)
    print(mything)
} catch {
    print(error)
}

最好将
JSON
粘贴到,并从中生成结构模型进行解码。希望这有助于解决任何与解码相关的困难。

这是正确的JSON吗?如果是,您应该调用
decode
作为
decode(ObjectReturned.self,from:data)
就是这样。谢谢谢谢由于我已经接受了另一个解释,所以我对你的深入回答投了赞成票。Quick type确实有正确的JSON解码器代码。是的,我必须以您建议的格式复制用于解析不同api的代码,并更改了对象名称,而不更改其余部分。不客气。由于缺乏关注,这是一个常见的错误。总之,快乐的编码:)Quicktype很棒,但偶尔它会生成很多辅助类。当这种情况发生时,你会努力改进吗?
do {
    let mything = try JSONDecoder().decode(ObjectsReturned.self, from: data)
    print(mything)
} catch {
    print(error)
}