Search code examples
iosswiftobjectmapper

How to map array using ObjectMapper?


Here is my model

class ResponseDataType: Mappable {

    var status: Int?
    var message: String?
    var info: [Info]?

    required init?(map: Map) { }

    func mapping(map: Map) {
        status <- map["status"]
        message <- map["message"]
        info <- map["member_info"]
    }
}

Here is my JSON

"status": 200,
    "data": {
        "member_info": [
            {
                "fullname": "werwerwer",
                "type": "werwer",
                "profile_image": "sdfsdfsd.jpg",
                "email": "wfwe@werwegt",
                "contact": ""
            }
        ]
    },
    "message": "Login Success"
}

Im having a hard time mapping the array inside the data. Please tell me what is wrong with my code.


Solution

  • You forgot the data. It should be like this:

    class ResponseDataType: Mappable {
    
    var status: Int?
    var message: String?
    var data: Data?
    
    required init?(map: Map) { }
    
    func mapping(map: Map) {
        status <- map["status"]
        message <- map["message"]
        data <- map["data"]
    }
    

    and your data class:

    class Data: Mappable {
    
    var info: [Info]?
    
    required init?(map: Map) { }
    
    func mapping(map: Map) {
        info <- map["member_info"]
    }