美文网首页
swift 读取本地json文件转model

swift 读取本地json文件转model

作者: wsj_2012 | 来源:发表于2020-07-08 14:09 被阅读0次

    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")
            }
    }
    

    相关文章

      网友评论

          本文标题:swift 读取本地json文件转model

          本文链接:https://www.haomeiwen.com/subject/djgsxktx.html