对象映射到根Json返回nil

时间:2016-08-25 11:44:53

标签: ios json swift alamofire objectmapper

我需要使用AlamofireObjectMapper映射以下Json:

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

我编写了以下代码部分,但映射对象返回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]
    }
}

这是发送帖子请求:

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)
}

映射root用户Json的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

我认为你必须制作两个可映射的对象;一个用于响应,另一个用于用户;像

//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
    }
}

现在

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

   //Do your work here


}

另一个选择是您要求后端开发人员删除该用户密钥并在单个字典中发送数据