1

我有一个这样的模型:

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将其映射到我的对象模型。

4

1 回答 1

1

如果需要返回值:

    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)
            }
        }
  }
于 2020-09-16T16:54:51.723 回答