我知道很多开源软件都有 JSON 反序列化功能,但您仍需要手动实现令人厌烦的映射函数。为了解决这个问题,我创建了 Mapper,使用 Objective-C 运行时,这样您就不再需要这样做。太棒了。
Mapper 可以与 Swift 对象(例如)集成,将 JSON 映射到对象,并将对象映射到 JSON,而无需手动实现。它非常简单易用。
pod "HPMapper"
// Create model inheritance Mapper class and that's all
// Objective-C (Recommended)
#import "Mapper.h"
@interface BaseModel : Mapper
@property (nonatomic, copy) NSString *ID;
@property (nonatomic, copy) NSString *Name;
@end
// Or Swift
class Carrot: Mapper {
dynamic var ID: NSString!
dynamic var Name: NSString!
}
let model = Model()
// Init it with json
model.initData(["Name": "Carrot", "ID": "A2jsdk"])
// Or simple
let model = Model(dictionary: ["Name": "This name", "ID": "This is ID from super class"])
model.toDictionary()
// Setup selector trigger
model.property("Name", target: self, selector: #selector(ChangeName), on: .onChange)
// Change value then ChangeName will be called
model.name = "New name"