首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用ObjectMapper绘制不同类型的地图?

如何使用ObjectMapper绘制不同类型的地图?
EN

Stack Overflow用户
提问于 2017-07-26 15:08:51
回答 3查看 3.7K关注 0票数 1

我使用ObjectMapper将JSON映射到Swift对象。

我有以下Swift对象:

代码语言:javascript
运行
复制
class User: Mappable {

    var name: String?
    var val: Int?

    required init?(map: Map) { }

    func mapping(map: Map) {
        name <- map["name"]
        val  <- map["userId"]
    }
}

我有一个JSON结构:

代码语言:javascript
运行
复制
{
   "name": "first",
   "userId": "1" // here is `String` type.
},
{
   "name": "second",
   "userId": 1 // here is `Int` type.
}

映射JSON后,userId of User ( name"first" )为null。

如何将Int/String映射到Int

EN

Stack Overflow用户

回答已采纳

发布于 2017-07-27 03:00:24

在阅读了ObjectMapper的代码之后,我找到了一种更容易解决问题的方法,就是定制转换。

代码语言:javascript
运行
复制
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函数的自定义转换。

代码语言:javascript
运行
复制
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.
    }
}

希望它能帮助那些有同样问题的人。:)

票数 6
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45330913

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档