關(guān)于ObjectMapper
關(guān)于這個(gè)第三方庫,我也是最近才接觸到,在轉(zhuǎn)到swift的項(xiàng)目當(dāng)中,其實(shí)很長(zhǎng)時(shí)間都在尋找一個(gè)適合庫來做網(wǎng)絡(luò)請(qǐng)求回來的JSON解析,但一直都沒有找到較好的,所以之前的項(xiàng)目一直都是手動(dòng)字典轉(zhuǎn)模型,最近發(fā)現(xiàn)了一個(gè)輕巧又實(shí)用的庫--而且再多層嵌套,也可以用幾句代碼完成轉(zhuǎn)換,簡(jiǎn)直可以媲美OC中字典轉(zhuǎn)模型的第三方框架.
Github的地址為:https://github.com/Hearst-DD/ObjectMapper
本文主要是翻譯github的內(nèi)容,大家如果英文閱讀能力較好的可以自己翻看英文文檔
基本使用方法
如果一個(gè)類或者結(jié)構(gòu)體的接口實(shí)現(xiàn)了Mappable接口的時(shí),便可以支持映射,然后還需要實(shí)現(xiàn)協(xié)議中的兩個(gè)接口:
init?(_ map: Map)mutating
func mapping(map: Map)
ObjectMapper實(shí)用了一個(gè)操作符 "<-"來定義成員變量的映射和JSON的轉(zhuǎn)換.
class User: Mappable {
//這里要定義好需要轉(zhuǎn)換的內(nèi)容相對(duì)于的字段和類型,以后日后方便賦值轉(zhuǎn)換
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?
required init?(_ map: Map) {
}
// Mappable
func mapping(map: Map) {
//根據(jù)字典中的內(nèi)容用"<-"操作符號(hào)來映射相應(yīng)的內(nèi)容,將其轉(zhuǎn)換到定義好的成員變量中
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())
}
}
//結(jié)構(gòu)體的話也是執(zhí)行相應(yīng)的操作
struct Temperature: Mappable {
var celsius: Double?
var fahrenheit: Double?
init?(_ map: Map) {
}
mutating func mapping(map: Map) {
celsius <- map["celsius"]
fahrenheit <- map["fahrenheit"]
}
}
唔,一旦你的類接口定義了Mappable,那么你這個(gè)類就可以調(diào)用簡(jiǎn)答的方法進(jìn)行字典轉(zhuǎn)模型的轉(zhuǎn)換啦.
轉(zhuǎn)換一個(gè)JSON成相應(yīng)的類模型:
let user = User(JSONSting:jsonString)
轉(zhuǎn)換一個(gè)模型成相應(yīng)的字符串:
let jsonString = user.toJSONString(prettyPrint:true)
除了這種轉(zhuǎn)換方式,Mapper.swfit類還提供了?擴(kuò)展的方法也可以進(jìn)行同樣的轉(zhuǎn)換:
// 字典轉(zhuǎn)模型
let user = Mapper<User>().map(JSONString: JSONString)
//字典轉(zhuǎn)模型
let JSONString = Mapper().toJSONString(user, prettyPrint: true)
ObjectMapper支持以下的數(shù)據(jù)類型
- 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
Mappable Protocol
mutating func mapping(map: Map)
這個(gè)函數(shù)里面定義了映射所需要指向的字符串,當(dāng)解析JSON的過程中,創(chuàng)建好實(shí)例對(duì)象以后會(huì)去執(zhí)行這個(gè)函數(shù),當(dāng)生成JSON的過程中,這個(gè)函數(shù)是唯一一個(gè)可以被叫做對(duì)象.
init?(_ map: Map)
//翻譯未完成,待續(xù)...其實(shí)ObjectMapper的使用非常簡(jiǎn)單,只要字符串和相對(duì)應(yīng)的Object一一對(duì)應(yīng)即可...