Ahmed Lotfy Ahmed Lotfy - 3 months ago 10
iOS Question

Object Mapping to the Root Json return nil

I need to map the following Json with AlamofireObjectMapper:

{
"user": {
"id": 2,
"first_name": "Dealer",
"last_name": "Seller",
"email": "seller@winfooz.com",
"authentication_token": "L6HzhZWdWhtxNwVkrsjY",
"documents_uploaded": false,
"type": "Dealer"
}
}


I wrote the following part of code, but the mapped object return nil!

class SystemUser:Mappable{
func mapping(map: Map) {
type <- map[SystemUserIdentifiers.UserType] //"type"
firstName <- map[SystemUserIdentifiers.FirstName]
lastName <- map[SystemUserIdentifiers.LastName]
internalIdentifier <- map[SystemUserIdentifiers.InternalIdentifier]
email <- map[SystemUserIdentifiers.Email]
documentsUploaded <- map[SystemUserIdentifiers.DocumentsUploaded]
authenticationToken <- map[SystemUserIdentifiers.AuthenticationToken]
}
}


Here is sending the post request:

Alamofire.request(.POST, URL, parameters: parameters, encoding: .JSON).responseObject {
(response: Response<SystemUser, NSError>) in

guard let user = response.result.value else{
return
}
print(user.authenticationToken)
}


What is the correct way to map rooted Json?

Answer

I think you'll have to make two mappable objects; one for response and another one for user; like

//Response
class ServerResponse:Mappable{
    var user: SystemUser?       
    func mapping(map: Map) {
        user <- map["user"]
    }
}

-

//User class
class SystemUser:Mappable{
    var type:String?
    var firstName:String?
    var lastName:String?
    // ... Further properties

    func mapping(map: Map) {
        type <- map["type"] //"type"
        firstName <- map["first_name"]
        lastName <- map["last_name"]
        // ... Further properties
    }
}

and now

Alamofire.request(.POST, URL, parameters: parameters, encoding: .JSON).responseObject {
            (response: Response<ServerResponse, NSError>) in
    print(response.user?.authenticationToken) 

   //Do your work here


}

Another option is that you ask backend developer to remove that user key and send data in single dictionary