将本地json文件解析为对象

时间:2018-05-22 12:13:19

标签: ios json swift swift3

我有这段代码:

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我有错误 (当应用程序启动时):解析文件typeMismatch的问题(Swift.Dictionary,Swift.DecodingError.Context(coding-path:[],debugDescription:"预期解码字典但是找到了一个数组。" ,underlyingError:will)。

如何解决?

1 个答案:

答案 0 :(得分:3)

当我在这里查看你的JSON http://json.parser.online.fr/时,有一个数组作为根对象,所以你应该这样做

let json = try JSONDecoder().decode([ProductObject].self, from: data)

<强>更新

请从此处json4swift创建JSON struct Codable,请先解决类型不匹配错误,否则无法解析您的JSON,并且会出现类型不匹配错误。

您可以通过以下方式获取产品代码,

let jsonData = try JSONDecoder().decode([ProductObject].self, from: data)

for detail in jsonData {
    print(detail.code ?? "")
}