首页 > 解决方案 > 将 json 文件导入对象错误

问题描述

我有这个 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: "期望解码 Dictionary 但找到了一个数组。",底层错误: nil))

我想将 json 写入 Products Object Array 对象数组。有人怎么修呢?

标签: iosswiftdecodable

解决方案


问题是Dictionary当 JSON 是Array

改变

let ProductsObjectArray = try decoder.decode(Products.self, from: data)

let ProductsObjectArray = try decoder.decode([Products].self, from: data)

推荐阅读