我有这个 json 文件: http://serwer1356363.home.pl/pub/json.txt
和这段代码:
var ProductsObjectArray = [Products]()
let data = try Data(contentsOf: path)
let decoder = JSONDecoder()
let ProductsObjectArray = try decoder.decode(Products.self, from: data)
型号:
struct ProductObject : Codable {
let palletHeight : Double?
let layerPallet : Int?
let prepCombisteamer : String?
let id : Int?
let prepOven : String?
}
当我启动此代码时,出现错误:
Swift.DecodingError.typeMismatch(Swift.Dictionary, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary but found an array instead.", underlyingError: nil))
我想将 json 写入 Products Object Array 对象数组。 有人可以修复它吗?
最佳答案
假设 ProductObject
按其应有的方式实现,并且您正在适本地从文件中读取数据:
如错误中所述:
"Expected to decode Dictionary but found an array instead."
json 文件包含 ProductObject
的数组,您的代码中似乎有 Products
,但不应该 用于解码器,可能你应该像这样解码它:
let ProductsObjectArray = try decoder.decode([ProductObject].self, from: data)
这意味着 ProductsObjectArray
将是 ProductObject
的数组。与字典无关。
旁注提示:在命名变量时,您应该遵循小驼峰命名法约定,而不是大驼峰命名法:
ProductsObjectArray
→ productsObjectArray
ProductsObjectArray
→ productsObjectArray
关于ios - 导入json文件到对象错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50832320/