使用 ObjectMapper 将字符串类型 JSON 转换为整数

Convert String type JSON to Integer with ObjectMapper

我有我的模型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**
}
}

我的输入 JSON 包含 optionId 作为字符串。

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

我需要在Objectmapper Map 函数中将这个传入的字符串类型转换为Int64。

有技巧可以使用

func mapping(map: Map) {
    let optionIdTemp: String?
    optionIdTemp <- map["id"]
    optionId = (optionIdTemp as? NSString)?.intValue
}

您可以创建自定义对象 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
    }
}

并在您的映射函数中使用此自定义 class 进行转换

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