Custom Mapping in HandyJSON subclass
HandyJSON
is a handy Swift JSON-Object serialization/deserialization library.
Sometimes there is some special key in you JSON data, for example:
{
"description": "Hi"
}
Since description
is a property of NSObject
for "a textual representation of an object", it's not a good idea to map the JSON description
to it, also it doesn't work if you want to. So we need to user Custom Mapping to map the value to another key, for example, desc
:
class BaseModel: NSObject, HandyJSON {
required override init() {}
}
class ChildModel: BaseModel {
var desc: String?
func mapping(mapper: HelpingMapper) {
mapper <<<
self.desc <-- "description"
}
}
let model = ChildModel.deserialize(from: "{\"description\":\"Hi\"}")
print(model?.desc as Any)
nil
It's a nil
here, what's wrong? After some digging, it turns out mapping
doesn't work in subclass, in order to make ti work, we need to put an empty mapping
in BaseModel
.
class BaseModel: NSObject, HandyJSON {
required override init() {}
func mapping(mapper: HelpingMapper) {
}
}
class ChildModel: BaseModel {
var desc: String?
override func mapping(mapper: HelpingMapper) {
mapper <<<
self.desc <-- "description"
}
}
let model = ChildModel.deserialize(from: "{\"description\":\"Hi\"}")
print(model?.desc as Any) // It's nil, what's wrong?
Hi
🚀🎉