Gloss bindings for Moya for fabulous JSON serialization. Supports RxSwift and ReactiveCocoa bindings as well.
Add to your Podfile:
pod 'Moya-Gloss'
The subspec(s) if you want to use the bindings over RxSwift or ReactiveCocoa.
pod 'Moya-Gloss/RxSwift'
pod 'Moya-Gloss/ReactiveCocoa'
github "spxrogers/Moya-Gloss"
Carthage lists Moya
and Gloss
as explicit dependencies, so it's only
necessary to list the above in your Cartfile and it will pull down all
three libraries. Carthage will generate three frameworks, MoyaGloss
,
RxMoyaGloss
, and ReactiveMoyaGloss
(following the naming convention of the
three generated frameworks from Moya).
Note: is only necessary to import one of these variations, otherwise Xcode will give you an "Ambiguous use..." error.
Create a Class
or Struct
which implements the Decodable
(or Glossy
) protocol.
import Foundation
import Gloss
struct Person: Decodable {
let name: String
let age: Int?
init?(json: JSON) {
guard let name: String = "name" <~~ json
else { return nil }
self.name = name
self.age = "age" <~~ json
}
}
mapObject()
mapObject(forKeyPath:)
mapArray()
mapArray(forKeyPath:)
provider.request(ExampleAPI.GetObject) { (result) in
switch result {
case .success(let response):
do {
let person = try response.mapObject(Person)
// *OR* the line below for a keyPath
// let person = try response.mapObject(Person.self, forKeyPath: "person")
print("Found person: \(person)")
} catch {
print(error)
}
case .failure(let error):
print(error)
}
}
provider.request(ExampleAPI.GetObject)
.mapObject(Person)
// *OR* the line below for a keyPath
// .mapObject(Person.self, forKeyPath: "multi.nested.person")
.subscribe { (event) in
switch event {
case .next(let person):
print("Found person: \(person)")
case .error(let error):
print(error)
default:
break
}
}
.addDisposableTo(your_preferred_dispose_bag)
provider.request(ExampleAPI.GetObject)
.mapObject(Person)
// *OR* the line below for a keyPath
// .mapObject(Person.self, forKeyPath: "person")
.start { (event) in
switch event {
case .value(let person):
print("Found person: \(person)")
case .failed(let error):
print(error)
default:
break
}
}
Issues and pull requests are welcome!
Steven Rogers @spxrogers
... to Harlan Kellaway for creating Gloss, my preferred JSON library :)
... to the Moya team for a wonderful network library.
... and finally, to the authors of the existing Moya community extensions for inspiring me to make one for Gloss.
Moya-Gloss is released under an MIT license. See LICENSE for more information.