簡體   English   中英

使用JSON中的JSON解碼器在JSON中解析integer值有困難Swift

[英]Difficulty parse integer value in JSON using JSON Decoder in Swift

我正在嘗試從 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: "Expected to decode Dictionary<String, Any> 但發現取而代之的是一個數字。”, underlyingError: nil))

此錯誤的原因可能是什么,我該如何解決?

感謝您的任何建議。

筆記:

解碼是通過:

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

您正在嘗試解碼錯誤的類型。 您的根 object 是單個ObjectsReturned實例,而不是[String:ObjectsReturned]

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

錯誤本身非常明顯,它表示您正在嘗試解碼DictionaryJSONDecoder找不到。 您可能從其他地方復制了這段代碼,這可能是犯此錯誤的原因。 model 應該只要看一眼就能算出來。 在這里您可以看到開頭沒有鍵,其值是預期的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粘貼到Quicktype並從那里生成結構 model 進行解碼。 希望這有助於解決任何JSON解碼相關的困難。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM