如何在 Swift5 中使用 ObjectMapper 映射 Alamofire 5.2 响应



我有一个这样的模型:

import UIKit
import ObjectMapper
struct Token: Mappable {
var token: String?
var deviceId: String?
init?(map: Map) {
}

mutating func mapping(map: Map) {
token <- map["token"]
deviceId <- map["device_id"]
}
}             

因此,请像这样向Alamofire发送请求:

import ObjectMapper
import Alamofire
override func viewDidLoad() {
super.viewDidLoad()
let request = ...
AF.request(request).validate(statusCode: 200..<300).responseJSON { (response:AFDataResponse<Any>) in
let token = Mapper<Token>().map(JSONString: serviceResponse.value) ‌//Not work   

}
}  

打印我的响应时是正确的,但是我无法使用ObjectMapper将其映射到我的对象模型。

如果需要返回值:

func getUserMapple(completionHandler: @escaping (_ userData: UserMappable) -> ()) {

guard let urlString = URL(string: userUrl) else { return }

AF.request(urlString).responseJSON { (responce) in

switch responce.result {
case .success(let value):
guard let castingValue = value as? [String: Any] else { return }
guard let userData = Mapper<UserMappable>().map(JSON: castingValue) else { return }
completionHandler(userData)
case .failure(let error):
print(error.localizedDescription)
}
}
}

如果需要返回数组:

func getUserMapple(completionHandler: @escaping (_ dotaData: [DotaModelMapable]) -> ()) {

guard let urlString = URL(string: dotaUrl) else { return }

AF.request(urlString).responseJSON { response in

switch response.result {
case .success(let value):
guard let dotaData = Mapper<DotaModelMapable>().mapArray(JSONObject: value) else { return }
completionHandler(dotaData)
case .failure(let error):
print(error.localizedDescription)
}
}
}

相关内容

  • 没有找到相关文章

最新更新