Search code examples
iosjsonswiftobjectmapper

Using cryptography with ObjectMapper


I have a class which it is being mapped with ObjectMapper. In the past the mapping worked fine, but a change in the project Architecture made the webservice return fields that were Double to a String with Cryptographed value.

is it possible to decryptograph and cast the webservice field into my class variable during the mapping?

This is what I have today:

class PosicaoConsolidada: Mappable {
    var portifolioBalance: Double!
    var families: [Family]!

    required init?(map: Map) {}

    public func mapping(map: Map) {
        portifolioBalance <- map["pointsBalance"]
        families <- map["fam"]
    }
}

This is what I imagine to do:

class PosicaoConsolidada: Mappable {
    var portifolioBalance: Double!
    var families: [Family]!

    required init?(map: Map) {}

    public func mapping(map: Map) {
        portifolioBalance <- Double(Decryptor.decrypt(map["pointsBalance"]))
        families <- map["fam"]
    }
}

Solution

  • There are several ways to accomplish the data decryption. ObjectMapper provides the protocol TransformType to deal with data transformations while mapping (reference).

    Transformer:

    import ObjectMapper
    
    class PointsTransform: TransformType {
        typealias Object = Double
        typealias JSON = String
    
        func transformFromJSON(_ value: Any?) -> Object? {
            guard let encoded = value as? String
                else { return nil }
    
            // TODO: Replace with decoding logic
            return 239_584.938
        }
    
        func transformToJSON(_ value: Object?) -> JSON? {
            guard let decoded = value
                else { return nil }
    
            return "\(decoded)"
        }
    }
    


    Model:

    class PosicaoConsolidada: Mappable {
        var portifolioBalance: Double!
        var families: [Family]!
    
        required init?(map: Map) {}
    
        public func mapping(map: Map) {
            portifolioBalance <- (map["pointsBalance"], PointsTransform())
            families <- map["fam"]
        }
    
    }