2

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.

Mannopson
  • 2,634
  • 1
  • 16
  • 32
NaXir
  • 2,373
  • 2
  • 24
  • 31

2 Answers2

12

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())
Indra Mohan
  • 455
  • 4
  • 13
2

there is trick to use that

func mapping(map: Map) {
    let optionIdTemp: String?
    optionIdTemp <- map["id"]
    optionId = (optionIdTemp as? NSString)?.intValue
}
Prabhjot Singh Gogana
  • 1,408
  • 1
  • 14
  • 39