Error: "Expected to decode Dictionary<String, Any> but found an array instead." — but I haven't defined a dictionary?

Error: "Expected to decode Dictionary<String, Any> but found an array instead." — but I haven't defined a dictionary?

我正在从事一个创意项目,我正在尝试使用 Swift 的 JSONDecoder() 函数从 API 数据库中解码内容。我已经构建了我的结构,一个 getData() 函数,并且我已经为 JSONDecoder() 函数设置了一个 do-try-catch。我很难理解我正在做什么来得到我遇到的错误。

这是我的结构:

struct Response: Codable {
    let foundRecipes: [Recipe]
    let foundIngredients: [Ingredient]
}

struct Recipe: Codable {
    let id: Int
    let title: String
    let image: String
    let imageType: String
    let usedIngredientCount: Int
    let missedIngredientCount: Int
    let missedIngredients: [Ingredient]
    let usedIngredients: [Ingredient]
    let unusedIngredients: [Ingredient]
    let likes: Int
}

struct Ingredient: Codable {
    let id: Int
    let amount: Int
    let unit: String
    let unitLong: String
    let unitShort: String
    let aisle: String
    let name: String
    let original: String
    let originalString: String
    let origianalName: String
    let metaInformation: [String]
    let meta: [String]
    let image: String
}

这是我的 getData() 函数:

    func getData(from url: String) {
    URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: { data, response, error in
        guard let data = data, error == nil else {
            print("something went wrong.")
            return
        }
        var result: Response?
        do {
            result = try JSONDecoder().decode(Response.self, from: data)
        }
        catch {
            print("")
            print(String(describing: error)) // Right here is where the error hits.
        }
        
        guard let json = result else {
            return
        }
        print(json.foundRecipes)
    }).resume()
}

这是 API 文档的 link。 URL 我在 getData() links 中调用相同的搜索结构,如他们的示例所示:https://spoonacular.com/food-api/docs#Search-Recipes-by-Ingredients — and here's a screenshot of the url results for the exact search I'm working on: https://imgur.com/a/K3Rn9SZ

最后,这是我发现的完整错误:

typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))

我对这个错误的理解是,它说我告诉 JSONDecoder() 寻找 的字典,但它在 link 并且只看到一个数组。我很困惑,因为我不知道它认为我在哪里提供字典。我哪里搞砸了?不寻找特定的代码更改,只是寻找有关我所缺少的内容的一些指导。

提前致谢:)

正如您在 API 数据图像和链接到的 API 文档中看到的那样,API 正在返回一个数组(例如,在文档中, 你可以看到它被 [...]) 包围了。事实上,它看起来像 API returns 一个 Recipe.

的数组

因此,您可以将解码调用更改为:

var result: [Recipe]?
do {
   result = try JSONDecoder().decode([Recipe].self, from: data)
   print(result)
} catch {
  print(error)
}

也许您对 Response 的想法来自其他地方,但是键 foundRecipesfoundIngredients 没有出现在这个特定的 API 调用中。


此外,感谢@workingdog 提供了关于将模型中的 amount 更改为 Double 而不是 Int 的有用评论。