1

如果我有:

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,一切都很好。使用正确的 id 创建了一个新的 Thing 结构。但是如果我想向 Thing 和硬代码添加“风味”怎么办{“id:“123”,“味道”:“某物”}。

即,让我们修改实际的 http 响应正文并"flavor": "something"在它到达 .mapObject 方法之前添加。哪里是利用它的正确位置?

这不仅仅是将它添加到 Thing 中的映射函数,因为每个 id 的“某物”都不同。可能是风味:“something1”,然后是风味:“something2”。我在与 callApi(id: id) 相同的范围内具有此值,因此类似于:

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

但这.addJSON是我刚刚编造的。它不存在。但是必须有一些简单的解决方案吗?

4

1 回答 1

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)。所以它本质上会在执行另一个映射后返回映射对象,该映射将添加您需要的任何必要信息。

于 2017-06-21T10:07:07.210 回答