Skip to content

Instantly share code, notes, and snippets.

@wanewang
Last active April 16, 2016 16:39
Show Gist options
  • Save wanewang/93b52c081dd2afe43cd7048a1fe0fcbf to your computer and use it in GitHub Desktop.
Save wanewang/93b52c081dd2afe43cd7048a1fe0fcbf to your computer and use it in GitHub Desktop.
import Foundation
import RxSwift
import Genome
import PureJsonSerializer
enum JsonError: String {
case CouldNotParseJSON
}
extension JsonError: ErrorType { }
extension Observable {
typealias Dictionary = [String: AnyObject]
/// Get given JSONified data, pass back objects
func mapToObject<B: MappableObject>(classType: B.Type) -> Observable<B> {
return self.map { json in
guard let dict = json as? Dictionary else {
throw JsonError.CouldNotParseJSON
}
return try B.newInstance(Json.from(dict))
}
}
/// Get given JSONified data, pass back objects as an array
func mapToObjectArray<B: MappableObject>(classType: B.Type) -> Observable<[B]> {
return self.map { json in
guard let array = json as? [AnyObject] else {
throw JsonError.CouldNotParseJSON
}
guard let dicts = array as? [Dictionary] else {
throw JsonError.CouldNotParseJSON
}
return dicts.flatMap { json -> B? in
do {
return try B.newInstance(Json.from(json))
} catch {
return nil
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment