You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

解析本地JSON到Swift对象失败,如何修复类型不匹配错误?

Fixing the "Expected to decode Dictionary but found an array instead" JSON Decoding Error in Swift

That error spells out exactly what's going wrong: your local JSON file holds an array of product objects, but your code is trying to decode it as a single ProductObject instance (which expects a JSON dictionary).

Here's how to fix this step by step:

  1. Adjust the decoding target type
    Instead of decoding to ProductObject.self, you need to target an array of that type: [ProductObject].self. This matches the top-level array structure in your JSON file.

  2. Update your code to handle the array
    Modify the decoder call to work with the array, then use the resulting collection (you can iterate through it, access individual elements, or process it however your app needs).

Here's your modified downloadImagesFromJsonProductFile function:

func downloadImagesFromJsonProductFile(fileName: URL){
    let filePath = fileName.path 
    let fileManager = FileManager.default 
    if fileManager.fileExists(atPath: filePath) { 
        do { 
            let data = try Data(contentsOf: fileName) 
            // Decode to an array of ProductObject instead of a single instance
            let products = try JSONDecoder().decode([ProductObject].self, from: data)
            
            // Example: Loop through the products to work with each one
            for product in products {
                print("Loaded product: \(product.name ?? "Unnamed product")")
                // Add your image download logic here using each product's properties
            }
        } catch let error { 
            self.errorLoginMessage(txt: "MainView - Error 109: Problem with parse file \(error)", title: "Blad".localized()) 
        } 
    } 
}

Why this fixes the issue:

  • A single ProductObject in Swift corresponds to a JSON dictionary (key-value pairs like {"name": "Sample Product", "id": 456}).
  • Your JSON file has a top-level array of these dictionaries (formatted like [{"name": "Product 1"}, {"name": "Product 2"}, ...]), so you need to decode to an array type to match that structure.

内容的提问来源于stack exchange,提问作者triff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:24:38