Search code examples
iosalamofireobjectmapper

Mappting Alamofire responseJSON via ObjectMapper


Note: I need to use ObjectMapper, and not AlamoFireObjectMapper.

How do you map without going to JSON but from responseJSON data to map to User? The following is trying to go from responseJSON to jsonn and then back again to data(being User). I guess there must be a way?

Or should I use responseData from AlamoFire?

public class User: Mappable {
    var username: String?

    required public init?(map: Map) {

    }

    // Mappable
    public func mapping(map: Map) {
        username    <- map["username"]
    }
}


    Alamofire.request(
        url,
        method: .get,
        headers: headers_employees).responseJSON {
            response in
        // Map via ObjectMapper
        let [User] = Mapper<User>().map(JSONString: JSONString)

   }

Solution

  • The map function also accepts a JSONObject (Any) or a JSON dictionary ([String: Any]). Depending on the type of the response object, you should use the appropriate method.

    In your case use below code to map JSONResponse

    Alamofire.request(
        url,
        method: .get,
        headers: headers_employees).responseJSON {
            response in
        // Map via ObjectMapper
        let [User] = Mapper<User>().map(JSONObject:response.result.value)
    }