如何将字段添加到Moya.Response JSON,这是不是在真正的有效载荷从HTTP响应
问题描述:
如果我有:如何将字段添加到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
是我编造的。它不存在。但是必须有一些简单的解决方案呢?
答
试图修改实际的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)。因此,它会在做出另一张地图之后基本上返回映射的对象,该地图会将所需的任何必要信息添加到其中。
最终直接与Alamofire进行每个http调用,然后很简单。如果有人很好奇,这是所有https://github.com/andrewarrow/boring_company_chat。 –