Moya with SwiftyJSON using Moya-SwiftyJSONMapper

I’ve just released Moya-SwiftyJSONMapper which makes it really easy to map MoyaResponse to a struct or model inheriting from the ALSwiftyJSONAble protocol in combination with SwiftyJSON.

Model creation with SwiftyJSON

After you’ve created your model:

import Foundation
import Moya_SwiftyJSONMapper
import SwiftyJSON

final class GetResponse : ALSwiftyJSONAble {

    let url:NSURL?
    let origin:String
    let args:[String: String]?

    required init?(jsonData:JSON){
        self.url = jsonData["url"].URL
        self.origin = jsonData["origin"].stringValue
        self.args = jsonData["args"].object as? [String : String]


You’re ready to go!

Usage with ReactiveCocoa or RxSwift

Either using ReactiveCocoa:

RCStubbedProvider.request(ExampleAPI.GetObject).mapObject(GetResponse).on(failed: { (error) -> () in
}) { (response) -> () in

using RxSwift:

let disposeBag = DisposeBag()

RXStubbedProvider.request(ExampleAPI.GetObject).mapObject(GetResponse).subscribe(onNext: { (response) -> Void in
}, onError: { (error) -> Void in

Or just without any functional programming frameworks:

stubbedProvider.request(ExampleAPI.GetObject) { (result) -> () in
    switch result {
    case let .Success(response):
        do {
            let getResponseObject = try response.mapObject(GetResponse)
        } catch {
    case let .Failure(error):

This makes it really nice to use Moya in combination with SwiftyJSON.


Antoine van der Lee

Dutch iOS developer at Triple. Developed apps like Buienradar, Videoland and Pop the Dots.

Follow on Feedly