Maha Khan Maha Khan -4 years ago 137
Swift Question

iOS Swift :Object mapper conditional mapping

I am new at swift , using object mapper for mapping, how can I map if message key is array in json or string it always return string.
Json Reponses


{ "error": {
"code": 404,
"messages": "message" } }

{ "error": {
"code": 406,
"messages": [
"message"
] } }


My Class

class Response : NSObject, Mappable {

var code : Int?
var data : AnyObject?
var message : [String]?


required init?(map: Map) {

}

func mapping(map: Map) {
code <- map["code"]
data <- map["data"]
message <- map["messages"]
}
}

Answer Source

You can create a custom Transform for transformations like this.

Create a class, that conforms to the TransformType protocol:

class ErrorMessagesTransform: TransformType {
    func transformFromJSON(_ value: Any?) -> Array<String>? {
        if let value = value as? String {
            return [value]
        }
        if let value = value as? [String] {
            return value
        }
        return []
    }

    func transformToJSON(_ value: Array<String>?) -> String? {
        // TODO: If needed
        return nil
    }
}

Then in your mapping function just do:

func mapping(map: Map) {
    code <- map["code"]
    data <- map["data"]
    message <- (map["messages"], ErrorMessagesTransform())
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download