将 json 文件导入对象错误
Import json file to object error
我有这个 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 对象数组。
有人怎么修?
问题是当 JSON 是 Array
时,您正试图解析 Dictionary
模型
改变
let ProductsObjectArray = try decoder.decode(Products.self, from: data)
到
let ProductsObjectArray = try decoder.decode([Products].self, from: data)
您的 JSON 包含顶级产品列表,因此您需要解码产品数组而不是单个字典。
尝试替换
let ProductsObjectArray = try decoder.decode(Products.self, from: data)
和
let ProductsObjectArray = try decoder.decode([Products].self, from: data)
假设 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
我有这个 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 对象数组。 有人怎么修?
问题是当 JSON 是 Array
Dictionary
模型
改变
let ProductsObjectArray = try decoder.decode(Products.self, from: data)
到
let ProductsObjectArray = try decoder.decode([Products].self, from: data)
您的 JSON 包含顶级产品列表,因此您需要解码产品数组而不是单个字典。
尝试替换
let ProductsObjectArray = try decoder.decode(Products.self, from: data)
和
let ProductsObjectArray = try decoder.decode([Products].self, from: data)
假设 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