美文网首页
Swift ObjectMapper 通用类配置

Swift ObjectMapper 通用类配置

作者: 孙国立 | 来源:发表于2021-02-20 09:16 被阅读0次
import Foundation
import RxSwift
import Moya
import ObjectMapper

extension Response {
    
    func mapObjectModel<T: BaseMappable>(_ type: T.Type, context: MapContext? = nil) throws -> T {
        guard let object = Mapper<T>(context: context).map(JSONObject: try mapJSON()) else {
            throw MoyaError.jsonMapping(self)
        }
        return object
    }
    
    func mapObjectArray<T: BaseMappable>(_ type: T.Type, context: MapContext? = nil) throws -> [T] {
        guard let array = try mapJSON() as? [[String : Any]] else {
            throw MoyaError.jsonMapping(self)
        }
        return Mapper<T>(context: context).mapArray(JSONArray: array)
    }
}

// MARK: - Json -> Observable<Model>

extension ObservableType where Element == Response {
    // 将Json解析为Observable<Model>
    public func mapObjectModel<T: BaseMappable>(_ type: T.Type) -> Observable<T> {
        return flatMap { response -> Observable<T> in
            return Observable.just(try response.mapObjectModel(T.self))
        }
    }
    // 将Json解析为Observable<[Model]>
    public func mapObjectArray<T: BaseMappable>(_ type: T.Type) -> Observable<[T]> {
        return flatMap { response -> Observable<[T]> in
            return Observable.just(try response.mapObjectArray(T.self))
        }
    }
}

相关文章

网友评论

      本文标题:Swift ObjectMapper 通用类配置

      本文链接:https://www.haomeiwen.com/subject/ofaoxltx.html