ModelMapper 为 Moya 提供的绑定,以便于使用 RxSwift 和 ReactiveCocoa 绑定进行更轻松的 JSON 序列化。
pod 'Moya-ModelMapper', '~> 10.0'
如果你想使用 RxSwift 的绑定,请使用以下子模块。
pod 'Moya-ModelMapper/RxSwift', '~> 10.0'
如果你想使用 ReactiveSwift 的绑定,请使用以下子模块。
pod 'Moya-ModelMapper/ReactiveSwift', '~> 10.0'
在 Cartfile 中指定
github "sunshinejr/Moya-ModelMapper" ~> 10.0
Carthage 用户可以指向此仓库并使用他们想要的任何生成的框架,Moya-ModelMapper、RxMoya-ModelMapper 或 ReactiveMoya-ModelMapper。
将以下内容作为依赖项添加到你的 Package.swift
文件中。
.package(url: "https://github.com/sunshinejr/Moya-ModelMapper.git", .upToNextMajor(from: "10.0.0"))
这些绑定通过 Moya_ModelMapper
模块提供。 如果你对响应式扩展感兴趣,请分别使用 ReactiveMoya_ModelMapper
或 RxMoya_ModelMapper
。
创建一个模型结构体或类。 它需要实现 Mappable 协议。
import Foundation
import Mapper
struct Repository: Mappable {
let identifier: Int
let language: String? // Optional property
let url: String? // Optional property
init(map: Mapper) throws {
try identifier = map.from("id")
language = map.optionalFrom("language")
url = map.optionalFrom("url")
}
}
然后你就可以使用扩展 Moya 响应的方法了。 这些方法是
map(to:)
map(to:keyPath:)
compactMap(to:)
compactMap(to:keyPath)
当使用 map(to:)
时,它尝试将整个响应数据映射到对象/数组,而使用 map(to:keyPath:)
,你可以指定响应中嵌套的对象进行获取。 例如,map(to: User.self, keyPath: "data.response.user")
将遍历 data 字典,再遍历 response 字典,最后到达 user 字典,然后对其进行解析。 compactMap
是数组 map
的变体,如果其中一个对象解析失败,它不会导致整个操作失败,而只会从数组中删除该对象。 RxSwift
和 ReactiveCocoa
扩展也拥有所有这些方法,但 RxSwift
额外具有可选映射。 请参阅下面的示例或 Demo 项目。
provider = MoyaProvider<GitHub>(endpointClosure: endpointClosure)
provider.request(GitHub.repos("mjacko")) { (result) in
if case .success(let response) = result {
do {
let repos = try response.map(to: [Repository].self)
print(repos)
} catch Error.jsonMapping(let error) {
print(try? error.mapString())
} catch {
print(":(")
}
}
}
provider = MoyaProvider<GitHub>(endpointClosure: endpointClosure)
provider.rx.request(GitHub.repo("Moya/Moya"))
.map(to: User.self, keyPath: "owner")
.subscribe { event in
switch event {
case .success(let user):
print(user)
case .error(let error):
print(error)
}
}
此外,RxSwift
的模块包含可选映射。 这基本上意味着如果映射失败,mapper 不会抛出错误,而是返回 nil。 例如
provider = MoyaProvider<GitHub>(endpointClosure: endpointClosure)
provider.rx.request(GitHub.repos("mjacko"))
.mapOptional(to: [Repository].self)
.subscribe { event in
switch event {
case .success(let repos):
// Here we can have either nil or [Repository] object.
print(repos)
case .error(let error):
print(error)
}
}
provider = MoyaProvider<GitHub>(endpointClosure: endpointClosure)
provider.reactive.request(GitHub.repos("mjacko"))
.map(to: [Repository].self)
.observeOn(UIScheduler())
.start { event in
switch event {
case .value(let repos):
print(repos)
case .failed(let error):
print(error)
default: break
}
}
Sunshinejr, thesunshinejr@gmail.com, @thesunshinejr
Moya-ModelMapper 在 MIT 许可证下可用。 有关更多信息,请参阅 LICENSE 文件。