swift 读取本地json文件转model

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

banner.json

{
  "banners": [
    {
      "imgUrl": "https://www.baidu.com/img/flexible/logo/pc/result@2.png",
      "action": "www.baidu.com",
      "actionInfo": {
        "url": "https://www.baidu.com",
        "tip": ""
      }
    },
    {
      "imgUrl": "https://www.baidu.com/img/flexible/logo/pc/result@2.png",
      "action": "",
      "actionInfo": {
        "url": "https://www.baidu.com",
        "tip": "提示"
      }
    },
    {
      "imgUrl": "https://www.baidu.com/img/flexible/logo/pc/result@2.png",
      "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")
        }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容