Swift 3 ObjectMapper - 将 URLSession 结果转换为 Map 对象失败

Posted

技术标签:

【中文标题】Swift 3 ObjectMapper - 将 URLSession 结果转换为 Map 对象失败【英文标题】:Swift 3 ObjectMapper - casting URLSession result to Map object fails 【发布时间】:2017-03-01 19:59:33 【问题描述】:

我应该如何使用 URLSession 获取 JSON 对象,以便能够从 ObjectMapper 将其转换为 Map 对象?这是我从 API 服务器获取数据的代码:

func makeGetRequest(completionHandler: @escaping ((AnyObject?) -> Void)) 
    let session = URLSession(configuration: .default)
    guard let requestUrl = URL(string:buildUrl()) else  return 
    var request = URLRequest(url:requestUrl)

    //HEADERS
    request.addValue("multipart/form-data; charset=utf-8", forHTTPHeaderField: "Content-Type");

    let token = CredentialsManager.sharedInstance().token;
    if (!(token?.isEmpty)!) 
        request.addValue(token!, forHTTPHeaderField: "X-Auth-Token");
    ;

    let task : URLSessionDataTask = session.dataTask(with: request, completionHandler: (data, response, error) in
        guard let data = data, error == nil else  return 
        do 
            let resultJSON = try JSONSerialization.jsonObject(with: data) as! [[String:AnyObject]]
            completionHandler(resultJSON as AnyObject?)
         catch let error as NSError 
            // Handle error
        
    );

    task.resume()

这是我要求获取数据的函数:

public func getUser() 
    makeGetRequest()  (result) -> Void in
        let resultModel = UserModel(map: result as! Map)
        self.resultDelegate.onUserRequestSuccess(model: resultModel!)
    

这是我实现可映射协议的 UserModel:

class UserModel : Mappable 

var id: Int?
var username: String?

required init?(map: Map) 



// Mappable
func mapping(map: Map) 
    id <- map["id"]
    username <- map["username"]

在调用时

UserModel(map: result as! Map)

我得到错误:

无法将“__NSDictionaryI”类型的值转换为“NSArray”

【问题讨论】:

【参考方案1】:

使用 JSONSerialization 获得响应是 ObjectMapper 的代码:

 let headers: HTTPHeaders = ["Accept": "application/json", "Authorization": authBearer]

 Alamofire.request(url, method: .get, parameters: nil, headers: headers).responseJSON  response  in
            print(response.result.value ?? "")
            let json = try! JSONSerialization.jsonObject(with: response.data!, options: [])
            let report = Mapper<Department>().map(JSON: json as! [String : Any])
            print(report?.department[0].employee[0].first_name ?? "")
 

class Department: Mappable 
    var department = [Directory]()

    required convenience init?(map: Map) 
        self.init()
    

    func mapping(map: Map) 
    department <- map["department"]
    



class Directory:Mappable 
    var id = 0
    var name = ""
    var employee = [Employee]()
    var genre = ""

    //Impl. of Mappable protocol
    required convenience init?(map: Map) 
        self.init()
    

    func mapping(map: Map) 
        id    <- map["id"]
        name <- map["name"]
        employee <- map["employee"]
        genre <- map["genre"]
    


class Employee: Mappable 
    var address = ""
    var dob = ""
    var email = ""
    var first_name = ""
    var last_name = ""
    var phone_number = ""

    required convenience init?(map: Map) 
        self.init()
    

    func mapping(map: Map) 
        address <- map["address"]
        dob <- map["dob"]
        email <- map["email"]
        first_name <- map["first_name"]
        last_name <- map["last_name"]
        phone_number <- map["phone_number"]

    

【讨论】:

以上是关于Swift 3 ObjectMapper - 将 URLSession 结果转换为 Map 对象失败的主要内容,如果未能解决你的问题,请参考以下文章

无法在 Swift 中导入 ObjectMapper

swift 使用ObjectMapper将数组转换为Realm的List类型

Swift:如何将带有 Alamofilre 或 SwiftyJSON 的 JSON 字符串转换为 ObjectMapper?

Swift 和 ObjectMapper:具有最小值的 NSDate

将 responseJSON 解析为 ObjectMapper

Swift - 嵌套对象的映射 (Objectmapper)