解析本地JSON到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:
Adjust the decoding target type
Instead of decoding toProductObject.self, you need to target an array of that type:[ProductObject].self. This matches the top-level array structure in your JSON file.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
ProductObjectin 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

