swift 读取本地json文件转model

1、准备一个.json的文件放入swift工程

banner.json

{
  "banners": [
    {
      "imgUrl": "https://www.baidu.com/img/flexible/logo/pc/[email protected]",
      "action": "www.baidu.com",
      "actionInfo": {
        "url": "https://www.baidu.com",
        "tip": ""
      }
    },
    {
      "imgUrl": "https://www.baidu.com/img/flexible/logo/pc/[email protected]",
      "action": "",
      "actionInfo": {
        "url": "https://www.baidu.com",
        "tip": "提示"
      }
    },
    {
      "imgUrl": "https://www.baidu.com/img/flexible/logo/pc/[email protected]",
      "action": "",
      "actionInfo": {
        "url": "https://www.baidu.com",
        "tip": "提示"
      }
    }
  ]
}

2、创建mode继承自Codable

BannerModel.swift

class BannerModel: Codable {
    var banners: [Banner]?
    
    class Banner: Codable {
        var imgUrl: String = ""
        var action: String = ""
        var actionInfo: ActionInfo?
        
        class ActionInfo: Codable {
            var url: String?
            var tip: String?
        }
    }
}

3、读取.json文件并转化为目标model

{
      guard let path = Bundle.main.path(forResource: "banner", ofType: "json") else { return }
      let localData = NSData.init(contentsOfFile: path)! as Data
      do {
            // banner即为我们要转化的目标model
            let banner = try JSONDecoder().decode(BannerModel.self, from: localData)
            if let banners = banner.banners {
                self.banners = banners
            }
        } catch {
            debugPrint("banner===ERROR")
        }
}

你可能感兴趣的:(swift 读取本地json文件转model)