在 swift 中使用 ObjectMapper 库映射字符串响应

mapping string response with ObjectMapper lib in swift

我尝试通过我的结果库使用对象映射器映射字符串响应。

这是结果 class :

import ObjectMapper

class Result< T : Mappable > : Mappable {

   var data: T?
   var status: String?
   var message: String?
   var error: String?

   init?(data: T?, status: String?, error: String?){
       self.data = data
       self.status = status
       self.error = error
   }

   required init?(map: Map){
   }

   func mapping(map: Map) {
       data    <- map["data"]
       status  <- map["status"]
       message <- map["message"]
       error   <- map["error"]
   }
}

这也是我的网络 class:

import Foundation
import ObjectMapper

final class Network<T:Mappable>{

init() {
}

open func requestItem(_ router: BaseRouter, completionHandler: @escaping (Any?, Error?) -> Void) {
    APIClient.Instance.requestJSON(router) { (response, error) in

        if let error = error {
            completionHandler(nil, APIError(code:ErrorCode.NetworkFailed, message:error.localizedDescription))
        }
        else if let json = response {

            var convertedString : String?

            do {
                let data1 =  try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted)
                convertedString = String(data: data1, encoding: String.Encoding.utf8)
                print(convertedString!.description)

            } catch let myJSONError {
                print(myJSONError)
            }

            let result : Result<T>? = Mapper<Result<T>>().map(JSONString: convertedString!)

            if let success = result?.status, success == "success" {
                completionHandler(result?.data, nil)
            }
            else {
                completionHandler(nil, APIError(code:ErrorCode.HandledInternalError, message:(result?.error)!))
            }
        }
        else {
            completionHandler(nil, APIError(code:ErrorCode.EmptyJSONException, message:"Empty JSON Exception"))
        }
    }
  }
}

响应是:

{
   "status" : "success",
   "data" : "01CPSE6AQXVK554MTGENETKW24"
}

我尝试映射它,但由于 String 不可映射 class,我做不到。 map["data"] 变量应该只分配字符串,而不是另一个复杂的 class。有没有人可以帮我解决这个问题?

最后的错误是:

我终于可以相信这段代码有什么问题了。

extension String : Mappable {

}

就这些了。