如何使用ObjectMapper映射不同的类型? [英] How to map different type using ObjectMapper?

查看:490
本文介绍了如何使用ObjectMapper映射不同的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ObjectMapper 将JSON映射到Swift对象.

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

我有以下Swift对象:

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"]
    }
}

我有这个JSON结构:

I have this JSON structure:

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

在映射JSON之后,UseruserId(其中name"first")为空.

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

如何将Int/String映射到Int?

推荐答案

阅读 ObjectMapper ,我发现了一种解决问题的简便方法,那就是自定义转换.

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)
    }
}

然后,对mapping函数使用自定义转换.

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. :)

这篇关于如何使用ObjectMapper映射不同的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆