美文网首页
Swift--字典转模型

Swift--字典转模型

作者: ibiaoma | 来源:发表于2018-05-21 17:27 被阅读102次

    1、 initWithDict

    这种方式最原始

    模型:

              class squareModel : NSObject {
              var ID : String?
              var name : String?
             var icon : String?
    
              init(dict: [String : Any]) {
                super.init()
                  ID = dict["id"] as? String
                name = dict["name"] as? String
                icon = dict["icon"] as? String
              }
        }
    

    解析:

          func loadData(completion: @escaping (_ dictM : DictModel) ->() )  {
                let url  = URL(string: "http://api.budejie.com/api/api_open.php")
                let params = ["a":"square", "c":"topic"]
        
                Alamofire.request(url!, method: HTTPMethod.get, parameters: params, encoding: URLEncoding.default , headers: nil).responseJSON { (response) in
                    switch response.result{
                    case .success(_):
                        guard let result = response.result.value else {
                            return
                        }
                        guard let dict = result as? [String : Any] else{
                           return
                        }
                        let dictModel = DictModel(dict: dict)
                        completion(dictModel)
                    case let .failure(error):
                        print(error)
                        break
                    }
                }
            }
    

    2、SwiftyJSON

    模型:

        class SwiftyModel: NSObject {
            var count : Int?
            var next_page : Int?
            var total : Int?
            var total_page : Int?
            var list : Array<listM>?
        }
        class listM: NSObject  {
            var fans_count: Int?
            var header: String?
            var uid: Int?
            var is_vip: Bool?
            var is_follow: Int?
            var introduction: String?
            var gender: Int?
            var tiezi_count : Int?
            var screen_name: String?
        }
    

    解析:

         func loadData(completion: @escaping (() -> ())){
                let url  = URL(string: "http://api.budejie.com/api/api_open.php")
                let params = ["a":"list", "c":"subscribe", "category_id":"35", "page":"1"]
                Alamofire.request(url!, method: .get, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
                    let json = JSON(response.result.value!)
                    self.swiftyModel.count = json["count"].int
                    self.swiftyModel.total = json["total"].int
                    self.swiftyModel.next_page = json["next_page"].int
                    self.swiftyModel.total_page = json["total_page"].int
                    guard let array = json["list"].array else{
                        return
                    }
                    var listArray :[listM] = [listM]()
                    for dic in array {
                        let list : listM  = listM()
                        list.header = dic["header"].string
                        list.introduction = dic["introduction"].string
                        list.fans_count = dic["fans_count"].int
                        listArray.append(list)
                    }
                    self.swiftyModel.list = listArray
                    completion()
                }
            }    
    

    3、HandyJSON

    模型:

        import HandyJSON
    
        class HandyModel : HandyJSON  {
            var info: infoModel_Handy = infoModel_Handy()
            var list: [list_Handy]? = [list_Handy]()
            //HandyJSON :模型为类必须添加 init方法,结构体则省略
            required init() { }
        }
        struct infoModel_Handy : HandyJSON{
            var vendor: String = ""
            var count  : Int = 0
            var page : Int = 0
            var maxid: String = ""
            var maxtime: String = ""
        }
        struct list_Handy : HandyJSON{
            var id : String = ""
            var type : String = ""
            var text: String = ""
            var name: String = ""
            var profile_image: String = ""
        }
    

    解析数据:

            func loadData(completion: @escaping (() -> ()))  {     
                let url  = URL(string: "http://api.budejie.com/api/api_open.php")
                let params = ["a":"newlist", "c":"data", "type":"all", "page":"1"]
                Alamofire.request(url!, method: .get, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
                    guard let dict : [String : Any] = response.result.value as? [String: Any] else {
                        return
                    }
                    if let handyM = HandyModel.deserialize(from: dict) {
                        self.handyModel = handyM
                    }
                    completion()
                  }
            }
    

    4、ObjectMapper

    模型:

        import ObjectMapper
    
        class ObjectMapperModel: Mappable {
            var count : Int?
            var next_page : Int?
            var  total : Int?
            var list : [listModel_Map]?
            required init?(map: Map) { }
            // Mappable
            func mapping(map: Map) {
                count       <- map["count"]
                next_page   <- map["next_page"]
                total       <- map["total"]
                list         <- map["list"]
            }
        }
        class listModel_Map : Mappable {
             var fans_count: Int?
            var header: String?
            var uid: Int?
            var is_vip: Bool?
            var is_follow: Int?
            var introduction: String?
            var gender: Int?
            var tiezi_count : Int?
            var screen_name: String?
            required init?(map: Map) { }
            // Mappable
            func mapping(map: Map) {
                fans_count           <- map["fans_count"]
                header               <- map["header"]
                uid                  <- map["uid"]
                is_vip               <- map["is_vip"]
                is_follow            <- map["is_follow"]
                introduction         <- map["introduction"]
                gender              <- map["gender"]
                tiezi_count         <- map["tiezi_count"]
                screen_name         <- map["screen_name"]
            }
        }
    

    解析:

            func loadData(completion: @escaping (() -> ())){
                let url  = URL(string: "http://api.budejie.com/api/api_open.php")
                let params = ["a":"list", "c":"subscribe", "category_id":"35", "page":"1"]
                Alamofire.request(url!, method: .get, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
                    guard let dict : [String : Any] = response.result.value as? [String: Any] else {
                        return
                    }  
                    let objectM = Mapper<ObjectMapperModel>().map(JSON: dict)
                    self.objectModel = objectM
                    completion()
                }
            }
    

    5、Codable

    这是Swift4新推出的

    模型

        struct CodableModel: Codable {
            var info : infoModel
            var list : [listModel]
            var total : Int
        }
        struct infoModel: Codable {
            var count : Int
            var np : Int
        }
        struct listModel : Codable {
            var count : Int
            var id : Int
            var name : String
        }
    

    解析:

        func loadData ( completion: @escaping (() -> ()))  {
                let url  = URL(string: "http://api.budejie.com/api/api_open.php")
                let params = ["a" : "category", "c" : "subscribe"]
                Alamofire.request(url!, method: .get, parameters: params , encoding: URLEncoding.default, headers: nil).responseData { (data) in
        //            do{
                        self.codableModel = try! JSONDecoder().decode(CodableModel.self, from: data.result.value!)
        //            }catch {
        //                //异常处理
        //            }
                    completion()
                }
            }
    

    附带Demo:
    https://gitee.com/iMaBiao/JSONDemo.git

    相关文章

      网友评论

          本文标题:Swift--字典转模型

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