【发布时间】:2018-11-01 04:54:06
【问题描述】:
我有这个代码:
struct ProductObject : Codable {
let palletHeight : Double?
let layerPallet : Int?
let prepCombisteamer : String?
let id : Int?
let avikoWorlds : [String]?
let avikoSegments : [String]?
let sunFlower : Bool?
let inPieces : Bool?
let noBox : Int?
let prepFryingPan : String?
let packageContents : Double?
let carbohydrates : Int?
let fat : Double?
let eanBox : Int?
let weightYieldPercent : Int?
let kcal : Int?
let markedAsFavourite1 : Bool?
let avikoPodSegmentyRynku : [String]?
let prepPot : String?
let prepMicrowave : String?
let name : String?
let code : Int?
let prepDeepFryer : String?
let avikoConcepts : [String]?
let boxLayer : Int?
let avikoSegmentyRynku : [String]?
let active : Bool?
let shelfLifeTimeFrame : String?
let markedAsFavourite2 : Bool?
let palletWeight : Double?
let changeTime : ChangeTime?
let kj : Int?
let langVersions : [LangVersions]?
let proteins : Double?
let markedAsFavourite3 : Bool?
let containsGluten : Bool?
let regions : [Int]?
let eanFoil : Int?
let shelfLife : Int?
let contentPerBox : Int?
let prepOven : String?
}
func downloadImagesFromJsonProductFile(fileName: URL){
let filePath = fileName.path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath) {
do {
let data = try Data(contentsOf: fileName)
let jsonData = try JSONDecoder().decode(ProductObject.self, from: data)
} catch let error {
self.errorLoginMessage(txt: "MainView - Error 109: Problem with parse file \(error)", title: "Blad".localized())
}
}
}
downloadImagesFromJsonProductFile(fileName: documentsDir.appendingPathComponent((AppGlobalManager.sharedManager.loggedUser?.selectedLanguage)! + "/json/products.json"))
我的本地json文件:https://files.fm/u/73n845ty
当我运行函数时:downloadImagesFromJsonProductFile 我有错误 (当应用程序启动时):解析文件类型不匹配(Swift.Dictionary,Swift.DecodingError.Context(coding-path:[],debugDescription:“期望解码字典但找到一个数组。”,基础错误:将)。
如何解决?
【问题讨论】:
-
让 jsonData = try JSONDecoder().decode([ProductObject].self, from: data)