-
Notifications
You must be signed in to change notification settings - Fork 648
映射器
xuyecan edited this page Sep 11, 2017
·
1 revision
HandyJSON
预先准备了一些常见非基本类型的Transform
可以使用。
class ExtendType: HandyJSON {
var date: Date?
var decimal: NSDecimalNumber?
var url: URL?
var data: Data?
var color: UIColor?
func mapping(mapper: HelpingMapper) {
mapper <<<
date <-- CustomDateFormatTransform(formatString: "yyyy-MM-dd")
mapper <<<
decimal <-- NSDecimalNumberTransform()
mapper <<<
url <-- URLTransform(shouldEncodeURLString: false)
mapper <<<
data <-- DataTransform()
mapper <<<
color <-- HexColorTransform()
}
public required init() {}
}
let object = ExtendType()
object.date = Date()
object.decimal = NSDecimalNumber(string: "1.23423414371298437124391243")
object.url = URL(string: "https://www.aliyun.com")
object.data = Data(base64Encoded: "aGVsbG8sIHdvcmxkIQ==")
object.color = UIColor.blue
print(object.toJSONString()!)
// it prints:
// {"date":"2017-09-11","decimal":"1.23423414371298437124391243","url":"https:\/\/www.aliyun.com","data":"aGVsbG8sIHdvcmxkIQ==","color":"0000FF"}
let mappedObject = ExtendType.deserialize(from: object.toJSONString()!)!
print(mappedObject.date)
...
映射器本质上是实现了TransformType
协议的类,那么我们可以定义自己的映射器,来做非基本类型的转化。
比如我们有一个代码中经常使用的枚举类型:
enum MyEnumType {
case type1, type2
}
因为它没有实现值类型,所以不能直接声明服从HandyJSONEnum
协议,那么我们就需要自定义转换规则了。为了方便,我们定义一个映射器:
class MyEnumTypeTransform: TransformType {
typealias Object = MyEnumType
typealias JSON = String
func transformFromJSON(_ value: Any?) -> MyEnumType? {
if let str = value as? String {
switch (str) {
case "type1":
return .type1
case "type2":
return .type2
default:
break
}
}
return nil
}
func transformToJSON(_ value: MyEnumType?) -> String? {
if let type = value {
switch (type) {
case .type1:
return "type1"
case .type2:
return "type2"
}
}
return nil
}
}
然后,我们就可以方便地使用这个映射器了:
class Model: HandyJSON {
var type: MyEnumType?
func mapping(mapper: HelpingMapper) {
mapper <<<
type <-- MyEnumTypeTransform()
}
required init() {}
}