序列化

ModelMapper(模型映射)

ObjectMapper can be added to your project using CocoaPods 0.36 or later by adding the following line to your Podfile:

pod 'ObjectMapper', '~> 1.1'

If you're using Carthage you can add a dependency on ObjectMapper by adding it to your Cartfile:

github "Hearst-DD/ObjectMapper" ~> 1.1

为了支持这种映射,一个类或者结构体必须实现Mappable这个接口。

public protocol Mappable {
init?(_ map: Map)
mutating func mapping(map: Map)
}

ObjectMapper使用<-操作符来定义如何将属性从JSON映射到对象:

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?
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())
}
}
struct Temperature: Mappable {
var celsius: Double?
var fahrenheit: Double?
init?(_ map: Map) {
}
mutating func mapping(map: Map) {
celsius <- map["celsius"]
fahrenheit <- map["fahrenheit"]
}
}