Search code examples
jsonswiftobjectmapper

How to map different type using ObjectMapper?


I'm using ObjectMapper to map my JSON to Swift object.

I have the following Swift object:

class User: Mappable {

    var name: String?
    var val: Int?

    required init?(map: Map) { }

    func mapping(map: Map) {
        name <- map["name"]
        val  <- map["userId"]
    }
}

I have this JSON structure:

{
   "name": "first",
   "userId": "1" // here is `String` type.
},
{
   "name": "second",
   "userId": 1 // here is `Int` type.
}

After mapping the JSON, the userId of User which name is "first" is null.

How can I map Int/String to Int?


Solution

  • After reading the code of ObjectMapper, I found an easier way to solve the problem, it's to custom the transform.

    public class IntTransform: TransformType {
    
        public typealias Object = Int
        public typealias JSON = Any?
    
        public init() {}
    
        public func transformFromJSON(_ value: Any?) -> Int? {
    
            var result: Int?
    
            guard let json = value else {
                return result
            }
    
            if json is Int {
                result = (json as! Int)
            }
            if json is String {
                result = Int(json as! String)
            }
    
            return result
        }
    
        public func transformToJSON(_ value: Int?) -> Any?? {
    
            guard let object = value else {
                return nil
            }
    
            return String(object)
        }
    }
    

    then, use the custom transform to the mapping function.

    class User: Mappable {
    
        var name: String?
        var userId: Int?
    
        required init?(map: Map) { }
    
        func mapping(map: Map) {
            name   <- map["name"]
            userId <- (map["userId"], IntTransform()) // here use the custom transform.
        }
    }
    

    Hope it can help others who have the same problem. :)