澳门新葡亰网址AlamofireObjectMapper[Swift学习笔记] ObjectMapper 框架。

        通常网络要返回的凡JSON数据,使用ObjectMapper可以于JSON数据直接转账为目标,而利用Alamofire进行网络要时,使用AlamofireObjectMapper可以一直归对象,更加简洁。

Hearst-DD/ObjectMapper

Podfile文件内容呢如下:

ObjectMapper是因此Swift语言实现目标及JSON相互转换的框架

source’https://github.com/CocoaPods/Specs.git’

platform:ios,’9.0′

use_frameworks!

target’Web’do

pod’AlamofireObjectMapper’,’~> 3.0′

end

xcodeproj’Desktop/Web/Web.xcodeproj’

ObjectMapper框架支持的数据结构类型:

target后面呢工程称为,最后一行也工程路径(这里的Web是自个儿的工程称为)

  • Int
  • Bool
  • Double
  • Float
  • String
  • RawRepresentable(Enums)
  • Array<AnyObject>
  • Dictionary<String, AnyObject>
  • 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 //上述的隐式解析只是选类型

外加操作:

其间Mappable是ObjectMapper框架中定义之一个接口

Target->工程名->Build Settings->Search Paths->User Header
Search Paths处添加AlamofireObjectMapper所在的目录:

public protocol Mappable {
 /// This function can be used to validate JSON prior to mapping.
 /// Return nil to cancel mapping at this point
 init?(_ map: Map)
 /// This function is where all variable mappings should occur. 
 ///It is executed by Mapper during the mapping (serialization and deserialization) process.
 mutating func mapping(map: Map)
}

末当公用用到AlamofireObjectMapper的好像吃加上:

配置

  • 以类型之podfile中添加:

pod 'ObjectMapper', '~> 1.3'
  • 运行 pod install

importAlamofireObjectMapper

案例

class User: Mappable {
    var username: String?
    var age: Int?
    var weight: Double!
    var array: [AnyObject]?
    var dictionary: [String : AnyObject] = [:]
    var bestFriend: User?                       // Nested User object
    var friends: [User]?                        // Array of Users
    var birthday: NSDate?
    var imageURLs: Array<NSURL>?

    required init?(_ map: Map) {

    }

    // 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())
        posterURL   <- (map["image"], URLTransform())
    }
}

自从定义之Model需要贯彻Mappable接口,并在mapping(map:
Map)方法中将Model的性与JSON结构的Key相映射,
如果ObjectMapper支持该属性的项目的变, 只待写

username <- map["username"]

倘ObjectMapper不支持转换就得调用Mappable额外提供的好像,
NSDate类型可以就此DateTransform()类易:

birthday <- (map["birthday"], DateTransform())

如ObjectMapper也没有供品类转化方法就是用打定义了变类了,
这里就是于定义了一个URLArrayTransform类:

import Foundation
import ObjectMapper

class URLArrayTransform: TransformType {
    typealias Object = Array<NSURL>
    typealias JSON = Array<AnyObject>

    init() {}

    func transformFromJSON(value: AnyObject?) -> Array<NSURL>? {
        if let URLStrings = value as? [String] {
            var listOfUrls = [NSURL]()
            for item in URLStrings {
                if let url = NSURL(string: item) {
                    listOfUrls.append(url)
                }
            }
            return listOfUrls
        }
        return nil
    }

    func transformToJSON(value: [NSURL]?) -> JSON? {
        if let urls = value {
            var urlStrings = [String]()
            for url in urls {
                urlStrings.append(url.absoluteString)
            }
            return urlStrings
        }

        return nil
    }
}

打定义的转换类需要贯彻 ObjectMapper 的 TransformType 接口, 从
URLArrayTransform 的实现中好看看自定义转换类还是比较简单的,
主要就还写 transformFromJSON 和 transformToJSON 方法.

整兑现了 User 类后, 就得是 User 和 JSON 字符串相互转换了

let user = User(JSONString: JSONString)

let JSONString = user.toJSONString(prettyPrint: true)  //prettyPrint参数用于生成JSON字符串是否格式化, 以便于打印

使用Mapper类转换
let user = Mapper<User>().map(JSONString: JSONString)

let JSONString = Mapper().toJSONString(user, prettyPrint: true)

补充: AlamofireObjectMapper

tristanhimmelman/AlamofireObjectMapper

欠框架可以组成 Alamofire 和 ObjectMapper 使用,
为Alamofire的Request类扩展出了responseObject 和 responseArray 方法,
更便于的拿网络通信返回的JSON数据易成靶子

创建 Mappable 对象

{

“args”:{},

“headers”:{    

“Accept”:”text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8″, 
  

“Accept-Encoding”:”gzip, deflate, br”,

 “Accept-Language”:”zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3″, 

 “Cache-Control”:”max-age=0″,    

 “Host”:”httpbin.org”,    

 “User-Agent”:”Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:46.0)
Gecko/20100101 Firefox/46.0″

},

“origin”:”202.115.52.218″,

“url”:”https://httpbin.org/get”

}

       
 根据拖欠JSON的多寡格式创建以下简单个Mapper类分别指向承诺总体字典和key值为“header”的字典。将JSON中之数与目标被的数目一一建立转化涉。
 

import ObjectMapper

class ResponseHeader: Mappable {

var accept : String?

var acceptEncoding : String?

var acceptLanguage : String?

var cacheControl : String?

var host : String?

var userAgent : String?

required init?(_ map: Map) {

}

//映射heades字典中之持有键值

func mapping(map: Map) {

accept <- map[“Accept”]

acceptEncoding <- map[“Accept-Encoding”]

acceptLanguage <- map[“Accept-Language”]

cacheControl <- map[“Cache-Control”]

host <- map[“Host”]

userAgent <- map[“User-Agent”]

}

}

import Foundation

import ObjectMapper

class MyResponse: Mappable {

var args : NSDictionary?

var headers : ResponseHeader?

var origin : String?

var url : String?

required init?(_ map: Map) {

}

//映射字典中之有着键值

func mapping(map: Map) {

args <- map[“args”]

headers <- map[“headers”]

origin <- map[“origin”]

url <- map[“url”]

}

}

配置

  • 每当档次的podfile中添加:

pod 'AlamofireObjectMapper', '~> 3.0'
  • 运行 pod install

用Alamofire获取对象

webRequst() { let url = “https://httpbin.org/get”
//注意返回的种类为Alamofire.request(.GET, url).responseObject {
(response: Response) in

let myResponse = response.result.value

print(myResponse?.url)

if let header = myResponse?.headers{

print(header.userAgent)

}

}

}

打印内容:

Optional(“https://httpbin.org/get”)

Optional(“Web/com.applelab.Web (1; OS Version 9.3 (Build 13E230))”)

Alamofire的使用:[速学会Swift第三方库]
Alamofire篇

ObjectMapper在非Alamofire请求下之采用:GitHub-ObjectMapper主页

案例

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

Leave a Comment.