Search code examples
jsonswiftrealmobjectmapper

Convert String type JSON to Integer with ObjectMapper


I have my model class

class CPOption : Object, Mappable
{

dynamic var optionId : Int64 = 0

override static func primaryKey() -> String? {
    return "optionId"
}

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

func mapping(map: Map) {

    optionId     <- map["id"] //**Here i need to transform string to Int64**
}
}

Where my input JSON contain optionId as String.

"options": [
            {
                "id": "5121",
            },
        ]

I need to convert this incoming string type to Int64 in Objectmapper Map function.


Solution

  • You can create custom object Transform class.

    class JSONStringToIntTransform: TransformType {
    
        typealias Object = Int64
        typealias JSON = String
    
        init() {}
        func transformFromJSON(_ value: Any?) -> Int64? {
            if let strValue = value as? String {
                return Int64(strValue)
            }
            return value as? Int64 ?? nil
        }
    
        func transformToJSON(_ value: Int64?) -> String? {
            if let intValue = value {
                return "\(intValue)"
            }
            return nil
        }
    }
    

    And use this custom class in your mapping function for the transformation

    optionId <- (map["id"], JSONStringToIntTransform())