我有這個問題很長一段時間了,但仍然沒有解決它。我正在嘗試從 URL 回應中解碼 JSON。我嘗試了很多事情,比如改變解碼器。對此
let productData = try JSONDecoder().decode([ProductDetail].self, from: data)
我得到的錯誤是
typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "product", intValue: nil)], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))
typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "product", intValue: nil)], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))
typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "product", intValue: nil)], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))
typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "product", intValue: nil)], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))
這是我的產品結構
struct ProductDetail: Codable {
var code: String?
var product: [Product?]
}
struct Product: Codable {
var _id: String?
var additives_tags: [String]? // [JSON?]
var allergens_tags: [String]?// [JSON?]
var brand_owner: String?
var countries_tags: [String]? // [JSON?]
var image_url: String?
var image_front_small_url: String?
var image_front_thumb_url: String?
var image_front_url: String?
var image_ingredients_small_url: String?
var image_ingredients_thumb_url: String?
var image_ingredients_url: String?
}
這是獲取功能
func fetchProduct(completionHandler: @escaping (ProductDetail) -> Void){
let url = URL(string: "https://world.openfoodfacts.org/api/v0/product/87222241")!
URLSession.shared.dataTask(with: url) { (data,
response, error) in
guard let data = data else { return}
do {
let productData = try JSONDecoder().decode(ProductDetail.self, from: data)
print(productData)
completionHandler(productData)
}catch {
let error = error
print(error)
}
}.resume()
}
json 檔案(https://world.openfoodfacts.org/api/v0/product/87222241)
{
"code": "87222241",
"product": {
"_id": "87222241",
"_keywords": [
"aa",
"drink"
],
"added_countries_tags": [],
"additives_debug_tags": [],
"additives_old_tags": [],
"additives_original_tags": [],
"additives_prev_original_tags": [],
"additives_tags": [],
"allergens": "",
"allergens_from_ingredients": "",
"allergens_from_user": "(fr) ",
"allergens_hierarchy": [],
"allergens_tags": [],
"amino_acids_prev_tags": [],
"amino_acids_tags": [],
"brands": "AA drink ",
"brands_tags": [
"aa-drink"
],
"categories_debug_tags": [],
"categories_hierarchy": [],
"categories_prev_hierarchy": [],
"categories_prev_tags": [],
"categories_properties": {},
uj5u.com熱心網友回復:
您已product在模型中定義為陣列。但是,正如錯誤所說,在 JSON 中,它是一個Dictionary. 將您的模型更改為:
struct ProductDetail: Codable {
var code: String?
var product: Product? //<-- Here
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/439298.html
