iOS必须Swift

ObjectMapper

2019-05-30  本文已影响0人  磊Se

基本介绍

特征

cocoaPods安装

模型类定义

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)

支持的类型

嵌套对象的简单映射

  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

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)           
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读