============
JASON bindings for Moya for easier JSON serialization with RxSwift and ReactiveCocoa bindings.
pod 'Moya-JASON', '1.0.0'
The subspec if you want to use the bindings over RxSwift.
pod 'Moya-JASON/RxSwift', '1.0.0'
And the subspec if you want to use the bindings over ReactiveCocoa.
pod 'Moya-JASON/ReactiveCocoa', '1.0.0'
Create a model struct or class. It needs to implement protocol Mappable.
import JASON
import Moya_JASON
private extension JSONKeys {
static let id = JSONKey<Int>("id")
static let language = JSONKey<String>("language")
static let url = JSONKey<String?>("url")
}
struct Repository: Mappable {
let identifier: Int
let language: String
let url: String?
init(_ json: JSON) throws {
identifier = json[.id]
language = json[.language]
url = json[.url]
}
}
import JASON
import Moya_JASON
public enum UserParsingError: Error {
case login
}
private extension JSONKeys {
static let login = JSONKey<String>("login")
}
struct User: Mappable {
let login: String
init(_ json: JSON) throws {
login = json[.login]
if login.isEmpty {
throw UserParsingError.login
}
}
}
Then you have methods that extends the response from Moya. These methods are:
mapObject()
mapObject(withKeyPath:)
mapArray()
mapArray(withKeyPath:)
While using mapObject()
tries to map whole response data to object,
with mapObject(withKeyPath:)
you can specify nested object in a response to
fetch. For example mapObject(withKeyPath: "owner")
. RxSwift
and ReactiveCocoa
extensions have all those methods as well.
provider = MoyaProvider<GitHub>()
provider.request(GitHub.repos("mjacko")) { (result) in
if case .success(let response) = result {
do {
let repos: [Repository] = try response.mapArray()
print(repos)
} catch {
print("There was something wrong with the mapping!")
}
}
}
provider = RxMoyaProvider<GitHub>()
provider
.request(GitHub.repo("Moya/Moya"))
.mapObject(User.self, keyPath: "owner")
.subscribe { event in
switch event {
case .next(let user):
print(user)
case .error(let error):
print(error)
default: break
}
}
provider = ReactiveCocoaMoyaProvider<GitHub>()
provider
.request(GitHub.repos("mjacko"))
.mapArray(Repository.self)
.observeOn(UIScheduler())
.start { event in
switch event {
case .value(let repos):
print(repos)
case .failed(let error):
print(error)
default: break
}
}
Sunshinejr, [email protected], @thesunshinejr
Moya-JASON is available under the MIT license. See the LICENSE file for more info.