Creign
Creign

Reputation: 134

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.

Upvotes: 0

Views: 70

Answers (2)

Kasım &#214;zdemir
Kasım &#214;zdemir

Reputation: 5634

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"]
}

Upvotes: 1

Dmitriy Lupych
Dmitriy Lupych

Reputation: 639

If your Info object conforms to Mappable, everything should work properly in your code. But try to read about Codable protocol, it’s much easier to map objects with it!

Upvotes: 0

Related Questions