2017-06-18 93 views
0

如果我有:如何將字段添加到Moya.Response JSON,這是不是在真正的有效載荷從HTTP響應

import Moya 
import RxSwift 
import ObjectMapper 
import Moya_ObjectMapper 

provider.request(.callApi(id: id)) 
     .mapObject(Thing.self) 
     .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background)) 
     .observeOn(MainScheduler.instance) 

...

struct Thing: Mappable, Equatable { 

    var id: String? 

    init?(map: Map) { 
    } 

    mutating func mapping(map: Map) { 
    id <- map["id"] 
    } 

發送HTTP api調用並返回類似於{「id:」123「}的json,並且它的運行效果很好,一個新的Thing結構是用正確的id創建的,但是如果我想爲Thing添加」flavor「並且硬編碼{」id :「123」,「味道」:「某物」}。

即我們只需修改實際的http響應主體並在它到達.mapObject方法之前添加"flavor": "something"。哪裏是正確的地方挖掘呢?

這不僅僅是將它添加到Thing中的映射函數中,因爲每個id的「something」是不同的。可能是味道:「東西1」,然後味道:「東西2」。我在相同的範圍內callApi這個值(ID:ID),所以像:

provider.request(.callApi(id: id)) 
     .addJSON("flavor", flavor) 
     .mapObject(Thing.self) 
     .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background)) 
     .observeOn(MainScheduler.instance) 

.addJSON是我編造的。它不存在。但是必須有一些簡單的解決方案呢?

+0

最終直接與Alamofire進行每個http調用,然後很簡單。如果有人很好奇,這是所有https://github.com/andrewarrow/boring_company_chat。 –

回答

0

試圖修改實際的JSON感覺髒,並在兩個低級別。但是,如果它有效,我一直在那裏等待着我。 :)

我會通過創建Moya_ObjectMapper提供的Moya.Response擴展方法的特殊版本來處理它。

public extension Response { 

    /// Maps data received from the signal into an object which implements the Mappable protocol. 
    /// If the conversion fails, the signal errors. 
    public func mapObject<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 
    } 

我會添加一個類似的方法,但有一個額外的參數閉包(T) - >(T)。因此,它會在做出另一張地圖之後基本上返回映射的對象,該地圖會將所需的任何必要信息添加到其中。