美文网首页iOS开发点滴ios developers
Swift开源项目ObjectMapper基本使用

Swift开源项目ObjectMapper基本使用

作者: 丶天空蓝丶 | 来源:发表于2023-04-24 14:25 被阅读0次

    最近开始研究一些swift的实用三方库,发现ObjectMapper是一个比较好用的json、模型相互转换的三方库。下面就总结一下ObjectMapper的一些基本使用

    一: 创建Model

    ObjectMapper中定义了一个协议Mappable,需要创建一个遵循协议的model,并实现协议中声明的两个方法

    class testModel: Mappable {
        var name: String! = ""
        var age: String! = ""
        required init?(map: Map) {
        }
        func mapping(map: ObjectMapper.Map) {
            name    <- map["name"]
            age    <- map["age"]
        }
    }
    

    二: 转Model

    单条数据转换

    提供的有map开头的四种方法可供使用,分别是JSON、JSONObject、JSONString、JSONfile。和直接用model初始化去转的JSON、JSONString两种方法

            let dic = ["name" : "zhangsan", "age" : "22"]
            
    //        字典转json字符串
            let data : Data! = try? JSONSerialization.data(withJSONObject: dic, options: []) as Data?
            let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
            
    //        需要传[String: Any]格式数据,也就是字典即可
            let model1 = Mapper<TestWSModel>().map(JSON: dic)
    //        传Any也就是任何格式数据都可以,但是我们点进去后可以发现,如果不是[String: Any]格式,直接返回nil
            let model2 = Mapper<TestWSModel>().map(JSONObject: dic)
            let model3 = Mapper<TestWSModel>().map(JSONObject: JSONString! as String)
    //        传string格式数据,也就是json字符串
            let model4 = Mapper<TestWSModel>().map(JSONString: JSONString! as String)
    //        传string格式数据,也就是文件路径(这里没测试)
            let model5 = Mapper<TestWSModel>().map(JSONfile: JSONString! as String)
    //        需要传[String: Any]格式数据,也就是字典即可
            let model6 = TestWSModel(JSON: dic)
    //        传string格式数据,也就是json字符串
            let model7 = TestWSModel(JSONString: JSONString! as String)
            
            printLog((model1?.name ?? "") as String)
            printLog((model2?.name ?? "") as String)
            printLog((model3?.name ?? "") as String)
            printLog((model4?.name ?? "") as String)
            printLog((model6?.name ?? "") as String)
            printLog((model7?.name ?? "") as String)
    

    输出结果:
    2023-04-24 14:16:31.543: zhangsan
    2023-04-24 14:16:31.556: zhangsan
    2023-04-24 14:16:31.556:
    2023-04-24 14:16:31.556: zhangsan
    2023-04-24 14:16:31.556: zhangsan
    2023-04-24 14:16:31.556: zhangsan

    正常来说单条数据转换基本实现字典或者json字符串转model即可,字典转使用JSON、JSONObject都可以,json字符串转使用JSONObject不报错,但是转换结果为nil,需要使用JSONString去转。

    另:这四个转换方法都对应有一个加toObject参数的转换方法

            let dic1 = ["userName" : "zhangsan", "age" : "22"]
            let dic2 = ["name" : "lisi", "age" : "23"]
    
            let model1 = Mapper<TestWSModel>().map(JSON: dic1, toObject: TestWSModel(JSON: dic2)!)
    
            printLog((model1.name ?? "") as String)
            printLog((model1.age ?? "") as String)
    

    输出结果:
    2023-04-24 14:33:17.414: lisi
    2023-04-24 14:33:17.431: 22

    可以发现转换后的model,name取得是dic2的值,age取得是dic1的值,也就是这个转换方法是现在dic1里面取值,如果没有对应的key则从toObject参数dic2里面取。

    mapDictionary开头方法使用

    let dic = ["name" : "zhangsan", "age" : "22"]
            let dic1 = ["person" : dic, "personnn" : dic,]
    //        使用方法上和map开头方法大致相同,只是在要转model的字典外面再加一层,相当于把要转model的字典当value
            let model = Mapper<TestWSModel>().mapDictionary(JSON: dic1, toDictionary: ["person" : TestWSModel(JSON: dic)!])
            printLog(model["person"]?.name)
    

    多条数据转换

    提供的有mapArray开头的四种方法可供使用,分别是JSONArray、JSONObject、JSONString、JSONfile。

            let dic = ["name" : "zhangsan", "age" : "22"]
            var array: [[String : Any]] = []
            for _ in 0 ..< 100 {
                array.append(dic)
            }
            
    //        数组转json字符串
            let data : Data! = try? JSONSerialization.data(withJSONObject: array, options: []) as Data?
            let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
            
    //        需要传[String: Any]格式的数组即可
            let array1 = Mapper<TestWSModel>().mapArray(JSONArray: array)
    //        传Any也就是任何格式数据都可以,但是我们点进去后可以发现,如果不是[String: Any]格式的数组,直接返回nil
            let array2 = Mapper<TestWSModel>().mapArray(JSONObject: array)
            let array3 = Mapper<TestWSModel>().mapArray(JSONObject: JSONString! as String)
    //        传string格式数据,也就是json字符串
            let array4 = Mapper<TestWSModel>().mapArray(JSONString: JSONString! as String)
    //        传string格式数据,也就是文件路径(这里没测试)
            let array5 = Mapper<TestWSModel>().mapArray(JSONfile: JSONString! as String)
            
            let model1 = array1[0]
            let model2 = array2?[0]
            let model3 = array3?[0]
            let model4 = array4?[0]
      
            printLog((model1.name ?? "") as String)
            printLog((model2?.name ?? "") as String)
            printLog((model3?.name ?? "") as String)
            printLog((model4?.name ?? "") as String)
    

    输出结果:
    2023-04-24 15:47:21.870: zhangsan
    2023-04-24 15:47:21.872: zhangsan
    2023-04-24 15:47:21.872:
    2023-04-24 15:47:21.872: zhangsan

    正常来说多条数据转换基本实现数组或者json字符串转model即可,数组转使用JSONArray、JSONObject都可以,json字符串转使用JSONObject不报错,但是转换结果为nil,需要使用JSONString去转。

    三: Model转出

    model转字典

         let dic1 =  model?.toJSON()
         let dic2 = Mapper().toJSON(model!)
    

    model转json字符串

          let jsonStr1 =  model?.toJSONString(prettyPrint: true)
          let jsonStr2 = Mapper().toJSONString(model!, prettyPrint: true)
    

    model数组转字典数组

          let array1 = array.toJSON()
          let array2 = Mapper().toJSONArray(array)
    

    四:转Model耗时

            let dic = ["name" : "zhangsan", "age" : "22"]
            var array: [[String : Any]] = []
            for _ in 0 ..< 500000 {
                array.append(dic)
            }
    //        数组转json字符串
            let data : Data! = try? JSONSerialization.data(withJSONObject: array, options: []) as Data?
            let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
    
            printLog("JSONArray数组转model开始")
    //        需要传[String: Any]格式的数组即可
            let array1 = Mapper<TestWSModel>().mapArray(JSONArray: array)
            printLog("JSONArray数组转model结束")
            printLog("JSONObject数组转model开始")
            let array2 = Mapper<TestWSModel>().mapArray(JSONObject: array)
            printLog("JSONObject数组转model结束")
            printLog("json字符串转model开始")
            let array3 = Mapper<TestWSModel>().mapArray(JSONString: JSONString! as String)
            printLog("json字符串转model结束")
    

    输出结果:
    2023-04-24 15:58:13.045: JSONArray数组转model开始
    2023-04-24 15:58:14.999: JSONArray数组转model结束
    2023-04-24 15:58:14.999: JSONObject数组转model开始
    2023-04-24 15:58:16.961: JSONObject数组转model结束
    2023-04-24 15:58:16.961: json字符串转model开始
    2023-04-24 15:58:20.195: json字符串转model结束

    对50万条2个字段数组进行转换,直接array转model,用JSONArray和JSONObject方法耗时大概一致,都是2秒左右,用json字符串转model则需要3秒多一点。

    同样50万条数据,进行不同处理后,使用JSONArray方法转换结果对比

    区别 时间
    2个字段,且对应value简单 2秒左右
    2个字段,且对应value复杂 2.1到2.2秒左右
    转换的数组为2个字段,对应模型10个字段 接近5秒
    转换的数组为10个字段,对应模型2个字段 2秒左右
    转换的数组为10个字段,对应模型10个字段 8.5秒左右

    可以发现时间跟转换的字段的多少关系比较大,字段长度关系不大

    四:初始化一个空model

    将NSObject协议添加到model里面,然后添加一个init方法即可

        class TestWSModel: NSObject,Mappable 
        
        override init() {
            super.init()
        }
        
       let model1: TestWSModel? = TestWSModel()
       model1?.name = "zhangsan"
    

    五:嵌套对象

    嵌套对象为字典,两种处理方法

    字典对象直接用当前model接收

    class TestWSModel: NSObject,Mappable {
        
        var name: String! = ""
        var achievement: Dictionary<String, Any>! = [:]
        var chinese: String! = ""
        var maths: String! = ""
        
        
        override init() {
            super.init()
        }
        required init?(map: Map) {
        }
        
        func mapping(map: ObjectMapper.Map) {
            name    <- map["name"]
            achievement    <- map["achievement"]
            chinese    <- map["achievement.chinese"]
            maths    <- map["achievement.maths"]
        }
    }
    
       let dic = ["name" : "zhangsan", "age" : "22", "achievement" : ["chinese" : "99", "maths" : "88"]] as [String : Any]
            //        需要传[String: Any]格式数据,也就是字典即可
            let model = Mapper<TestWSModel>().map(JSON: dic)
            printLog(model?.name)
            printLog(model?.achievement)
            printLog(model?.chinese)
            printLog(model?.maths)
    

    输出结果:
    2023-04-25 13:57:28.781: Optional("zhangsan")
    2023-04-25 13:57:28.783: Optional(["chinese": "99", "maths": "88"])
    2023-04-25 13:57:28.784: Optional("99")
    2023-04-25 13:57:28.784: Optional("88")

    字典用另外一个model接收

    class TestWSModel: NSObject,Mappable {
        
        var name: String! = ""
        var achievement: achievementModel! = AchievementModel()
        
        
        override init() {
            super.init()
        }
        required init?(map: Map) {
        }
        
        func mapping(map: ObjectMapper.Map) {
            name    <- map["name"]
            achievement    <- map["achievement"]
        }
    }
    
    
    class AchievementModel: NSObject,Mappable {
        
        var chinese: String! = ""
        var maths: String! = ""
        
        override init() {
            super.init()
        }
        required init?(map: Map) {
        }
        
        func mapping(map: ObjectMapper.Map) {
            chinese    <- map["chinese"]
            maths    <- map["maths"]
        }
    }
    
           let dic = ["name" : "zhangsan", "age" : "22", "achievement" : ["chinese" : "99", "maths" : "88"]] as [String : Any]
            //        需要传[String: Any]格式数据,也就是字典即可
            let model = Mapper<TestWSModel>().map(JSON: dic)
            printLog(model?.name)
            printLog(model?.achievement)
            printLog(model?.achievement.chinese)
            printLog(model?.achievement.maths)
    

    输出结果:
    2023-04-25 14:01:06.049: Optional("zhangsan")
    2023-04-25 14:01:06.051: Optional(<TestSwift.AchievementModel: 0x600001fc8720>)
    2023-04-25 14:01:06.051: Optional("99")
    2023-04-25 14:01:06.051: Optional("88")

    嵌套对象为数组

    class TestWSModel: NSObject,Mappable {
        
        var name: String! = ""
        var achievement: Array<AchievementModel>! = []
        
        override init() {
            super.init()
        }
        required init?(map: Map) {
        }
        
        func mapping(map: ObjectMapper.Map) {
            name    <- map["name"]
            achievement    <- map["achievement"]
        }
    }
    
    
    class AchievementModel: NSObject,Mappable {
        
        var chinese: String! = ""
        var maths: String! = ""
        
        override init() {
            super.init()
        }
        required init?(map: Map) {
        }
        
        func mapping(map: ObjectMapper.Map) {
            chinese    <- map["chinese"]
            maths    <- map["maths"]
        }
    }
    
          let dic = ["name" : "zhangsan", "age" : "22", "achievement" : [["chinese" : "99", "maths" : "88"], ["chinese" : "77", "maths" : "66"]]] as [String : Any]
            //        需要传[String: Any]格式数据,也就是字典即可
            let model = Mapper<TestWSModel>().map(JSON: dic)
            printLog(model?.name)
            printLog(model?.achievement)
            
            for achModel in model!.achievement {
                printLog(achModel.chinese)
                printLog(achModel.maths)
            }
    

    输出结果:
    2023-04-25 14:25:08.579: Optional("zhangsan")
    2023-04-25 14:25:08.581: Optional([<TestSwift.AchievementModel: 0x6000005d2820>, <TestSwift.AchievementModel: 0x6000005d23d0>])
    2023-04-25 14:25:08.582: Optional("99")
    2023-04-25 14:25:08.582: Optional("88")
    2023-04-25 14:25:08.582: Optional("77")
    2023-04-25 14:25:08.582: Optional("66")

    相关文章

      网友评论

        本文标题:Swift开源项目ObjectMapper基本使用

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