Skip to content

自定义映射规则

xuyecan edited this page Sep 11, 2017 · 1 revision

自定义解析路径

HandyJSON支持自定义映射关系,你需要实现一个可选的mapping函数,通过xx.xx.xxx的形式指定一个属性的解析路径。.为分隔符,如果路径的某个key包含了.本身,需要用\转义。

class Cat: HandyJSON {
    var id: Int64!
    var name: String!
    var friendName: String?

    required init() {}

    func mapping(mapper: HelpingMapper) {
        // specify 'friend.name' path field in json map to 'friendName' property
        mapper <<<
            self.friendName <-- "friend.name"
    }
}

let jsonString = "{\"cat_id\":12345,\"name\":\"Kitty\",\"parent\":\"Tom/Lily\",\"friend\":{\"id\":54321,\"name\":\"Lily\"}}"

if let cat = Cat.deserialize(from: jsonString) {
    print(cat.friendName)
}

自定义解析过程

HandyJSON支持自定义解析过程,在mapping里边实现String值(HandyJSON会把对应的JSON字段转换为String)转换为你需要的字段类型。

class Cat: HandyJSON {
    var id: Int64!
    var name: String!
    var parent: (String, String)?

    required init() {}

    func mapping(mapper: HelpingMapper) {
        // specify 'parent' field in json parse as following to 'parent' property in object
        mapper <<<
            self.parent <-- TransformOf<(String, String), String>(fromJSON: { (rawString) -> (String, String)? in
                if let parentNames = rawString?.characters.split(separator: "/").map(String.init) {
                    return (parentNames[0], parentNames[1])
                }
                return nil
            }, toJSON: { (tuple) -> String? in
                if let _tuple = tuple {
                    return "\(_tuple.0)/\(_tuple.1)"
                }
                return nil
            })
    }
}

let jsonString = "{\"cat_id\":12345,\"name\":\"Kitty\",\"parent\":\"Tom/Lily\",\"friend\":{\"id\":54321,\"name\":\"Lily\"}}"

if let cat = Cat.deserialize(from: jsonString) {
    print(cat.id)
    print(cat.parent)
}