为了使用这个特性,需要先创建一个对象实现了 MapContext 协议(这个协议是空的),然后在初始化时传入 Mapper 中。
struct Context: MapContext { var importantMappingInfo = "映射时需要知道的额外信息" } class User: Mappable { var name: String? required init?(map: Map){ } func mapping(map: Map){ if let context = map.context as? Context { // 获取到额外的信息 } } } let context = Context() let user = Mapper<User>(context: context).map(JSONString) ObjectMapper + Alamofire如果网络层你使用的是Alamofire ,并且你希望把返回的结果转换成 Swift 对象,你可以使用 AlamofireObjectMapper 。这是一个使用 ObjectMapper 实现的把返回的 JSON 自动转成 Swift 对象的 Alamofire 的扩展。
ObjectMapper + RealmObjectMapper 可以和 Realm 一起配合使用。使用下面的声明结构就可以使用 ObjectMapper 生成 Realm 对象:
class Model: Object, Mappable { dynamic var name = "" required convenience init?(map: Map) { self.init() } func mapping(map: Map) { name <- map["name"] } }如果你想要序列化相关联的 RealmObject,你可以使用ObjectMapper+Realm。这是一个简单的 Realm 扩展,用于把任意的 JSON 序列化成 Realm 的类(ealm's List class。)
注意:使用 ObjectMappers 的 toJSON 函数来生成 JSON 字符串只在 Realm 的写事务中有效(write transaction)。这是因为 ObjectMapper 在解析和生成时在映射函数( <- )中使用 inout 作为标记( flag )。Realm 会检测到标记并且强制要求 toJSON 函数只能在一个写的事务中调用,即使这个对象并没有被修改。
待完成如果你的项目使用 CocoaPods 0.36 及以上 的版本,你可以把下面内容添加到在 Podfile 中,将 ObjectMapper 添加到你的项目中:
pod 'ObjectMapper', '~> 2.2' Carthage如果你的项目使用Carthage ,你可以把下面的内容添加到 Cartfile 中,将 ObjectMapper 的依赖到你的项目中:
github "Hearst-DD/ObjectMapper" ~> 2.2 Swift Package Manager如果你的项目使用 Swift Package Manager ,那么你可以把下面内容添加到 Package.swift 中的 dependencies 数组中,将 ObjectMapper 的依赖到你的项目中:
.Package(url: "https://github.com/Hearst-DD/ObjectMapper.git", majorVersion: 2, minor: 2), Submodule此外,ObjectMapper 也可以作为一个 submodule 添加到项目中:
分享给小伙伴们:
本文标签: ObjectMapper/">ObjectMapper
相关文章
发表评论愿您的每句评论,都能给大家的生活添色彩,带来共鸣,带来思索,带来快乐。