我已经有很长一段时间没有解决这个问题了。我正在尝试从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": {},
发布于 2022-03-07 19:36:05
您已经将product
定义为模型中的数组。但是,正如错误说的那样,在JSON中,它是一个Dictionary
。将模型更改为:
struct ProductDetail: Codable {
var code: String?
var product: Product? //<-- Here
}
https://stackoverflow.com/questions/71386328
复制相似问题