Search code examples
jsonswiftobjectmapper

ObjectMapper parsing generic object


I got error when parsing generic object with ObjectMapper Here is my classes:

class BaseResponse<T>: NSObject, Mappable {
    var isSuccess: Bool!
    var data: T?

    required init?(map: Map) {
        super.init()
        self.mapping(map: map)
    }

    func mapping(map: Map) {
        isSuccess <- map["success"]
        data <- map["data"]
    }
}

class Login: NSObject, Mappable {
    var isProfileUpdated: Bool?
    var role: String!
    var profileId: Int!
    var email: String!

    override func mapping(map: Map) {
        isProfileUpdated <- map["profile_updated"]
        role <- map["role"]
        profileId <- map["id"]
        email <- map["email"]
    }
}

I parsed this json:

{
     "token" : "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MTU4MDkzODAuNjg4LCJpYXQiOjE1MTU3MjI5ODAuNjg4LCJpc3MiOiJleWUtc29sdXRpb24udm4iLCJpZCI6MTgsInJvbGUiOiJlbXBsb3llZSIsInNfaWQiOjg5LCJwX2lkIjoxMX0.v8iEgEXlXGzv5HmDvWs-tUNNYZFBQqCtTLaUkgqXqM0",
     "data" : {
        "email" : "at.ce90@gmail.com",
        "id" : 18,
        "profile_updated" : false,
        "updated_at" : "2018-01-08T05:51:19.045Z",
        "created_at" : "2018-01-08T05:50:51.517Z",
        "avatar_id" : null,
        "referral_code" : "BFHw6I",
        "active" : true,
        "role" : "employee",
        "referral_id" : null
      },
    "success" : true
}

via this function:

let response = Mapper<BaseResponse<Login>>().map(JSONString: jsonString)

response.data = nil after parsing. I have no idea. Anyone knows why?


Solution

  • I found solution:

    class BaseResponse<T>: NSObject, Mappable where T: Mappable {
        var isSuccess: Bool!
        var data: T?
    
        required init?(map: Map) {
            super.init()
            self.mapping(map: map)
        }
    
        func mapping(map: Map) {
            isSuccess <- map["success"]
            data <- map["data"]
        }
    }
    

    Everything works fine. Hope this help anyone like me.