ObjectMapper

作者: 磊Se | 来源:发表于2019-05-30 16:29 被阅读0次

    基本介绍

    特征

    • 将JSON映射到对象
    • 将对象映射到JSON
    • 支持嵌套对象(在数组或字典中单独使用)
    • 支持映射过程中自定义转换
    • 支持结构体
    • 支持Immutable

    cocoaPods安装

    • pod 'ObjectMapper'

    模型类定义

    • 创建模型类需要实现Mappable接口,包括init?(map: Map)func mapping(map: Map)俩方法
    • ObjectMapper使用<-特殊运算符表示JSON与模型属性之间的映射关系
    class User: Mappable {
        var username: String?
        var age: Int?
        var weight: Double!
        var array: [Any]?
        var dictionary: [String : Any] = [:]
        var bestFriend: User?                       // Nested User object
        var friends: [User]?                        // Array of Users
        var birthday: Date?
    
    //对象序列号之前验证JSON合法性,不符合条件返回nil阻止映射发生
        required init?(map: Map) {
          // 检查JSON是否有name字段
          if map.JSON["name"] == nil {
            return nil
          }
        }
    
        // Mappable
        func mapping(map: Map) {
            username    <- map["username"]
            age         <- map["age"]
            weight      <- map["weight"]
            array       <- map["arr"]
            dictionary  <- map["dict"]
            bestFriend  <- map["best_friend"]
            friends     <- map["friends"]
            birthday    <- (map["birthday"], DateTransform())
        }
    }
    
    struct Temperature: Mappable {
        var celsius: Double?
        var fahrenheit: Double?
    
        init?(map: Map) {
    
        }
    
        mutating func mapping(map: Map) {
            celsius     <- map["celsius"]
            fahrenheit  <- map["fahrenheit"]
        }
    }
    

    数据转换

    JSON字符串转模型类
    let user = User(JSONString: JSONString)
    //使用Mapper
    let user = Mapper<User>().map(JSONString: JSONString)
    //使用Mapper转模型数组
    let users: [User] = Mapper<User>().mapArray(JSONString: JSONString)
    
    模型类转JSON字符串
    //prettyPrint参数是为了打印可读性json
    let JSONString = user.toJSONString(prettyPrint: true)
    //使用Mapper
    let JSONString = Mapper().toJSONString(users, prettyPrint: true)
    

    支持的类型

    • Int
    • Bool
    • Double
    • Float
    • String
    • RawRepresentable (Enums)
    • Array<Any>
    • Dictionary<String, Any>
    • Object<T: Mappable>
    • Array<T: Mappable>
    • Array<Array<T: Mappable>>
    • Set<T: Mappable>
    • Dictionary<String, T: Mappable>
    • Dictionary<String, Array<T: Mappable>>
    • Optionals of all the above //上述的可选类型
    • Implicitly Unwrapped Optionals of the above //上述的隐式解析可选类型

    嵌套对象的简单映射

      import ObjectMapper
    
    class UserInfo: Mappable {
        var username: String?
        var age: Int?
        var weight: Double!
        var dictionary: UserInfo?
        var value: String?
    
    
        required init?(map: Map) {
        }
        
        func mapping(map: Map) {
            username    <- map["username"]
            age         <- map["age"]
            weight      <- map["weight"]
            dictionary  <- map["dictionary"]
            value  <- map["dictionary.username"]
        }
    }
    

    自定义转换

    ObjectMapper提供了一些类型转换如DateTransform、DataTransform、HexColorTransform,但是没有提供的就需要我们自定义,下面举例实现NSURLTransform

    • 实现TransformType接口
    import UIKit
    import ObjectMapper
    
    class NSURLTransform: TransformType {
        typealias Object = NSURL
        typealias JSON = String
        
        func transformFromJSON(_ value: Any?) -> NSURL? {
            guard let string = value as? String else{
                return nil
            }
            return NSURL.init(string: string)
        }
        
        func transformToJSON(_ value: NSURL?) -> String? {
            guard let url = value else{
                return nil
            }
            return url.absoluteString
        }
    
    }
    

    补充:AlamofireObjectMapper

    该框架可以结合 Alamofire 和 ObjectMapper 使用, 为Alamofire的Request类扩展出了responseObject 和 responseArray 方法, 更方便的将网络通信返回的JSON数据转换成对象

    let URL = "..."
    Alamofire.request(.GET, URL).responseObject { (response: DataResponse<WeatherResponse>) in
    
        let weatherResponse = response.result.value
    
        if let threeDayForecast = weatherResponse?.threeDayForecast {
            for forecast in threeDayForecast {
                print(forecast.day)
                print(forecast.temperature)           
            }
        }
    }
    

    相关文章

      网友评论

        本文标题:ObjectMapper

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