这里要说的重点不是在与JsonModel 本身有的方法的常规写法,而是如何全局忽略无关属性.(每个Model 都写一下下面的方法,岂不是很蛋(^))
方式一.可选属性 (就是说这个属性可以为null或者为空)
{
"id": "123",
"name": null,
"price": 12.95
}
@interface ProductModel : JSONModel
@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString<Optional>* name;
@property (assign, nonatomic) float price;
@property (strong, nonatomic) NSNumber<Optional>* uuid;
@end
@implementation ProductModel
@end
方式二.忽略属性 (就是完全忽略这个属性)
{
"id": "123",
"name": null
}
@interface ProductModel : JSONModel
@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString<Ignore>* customProperty;
@end
@implementation ProductModel
@end
方式三.设置所有的属性为可选(所有属性值可以为空)
@implementation ProductModel
+(BOOL)propertyIsOptional:(NSString*)propertyName
{
return YES;
}
@end
重点在这里 propertyIsOptional
方法默认返回的是NO;拦截该方法,使其返回YES.(当然,如果你修改JsonModel 源码,当我没说)
#import "objc/runtime.h"
@implementation JSONModel (SafeJSONModel)
+(void)load{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
SEL org_Selector = @selector(propertyIsOptional:);
SEL dt_Selector = @selector(dt_propertyIsOptional:);
Method org_method = class_getClassMethod([self class], org_Selector);
Method dt_method = class_getClassMethod([self class], dt_Selector);
class_addMethod(self, org_Selector, method_getImplementation(dt_method), method_getTypeEncoding(dt_method));
// if (isAdd) {
// class_replaceMethod(self, dt_Selector, method_getImplementation(org_method), method_getTypeEncoding(org_method));
// }else{
method_exchangeImplementations(org_method, dt_method);
// }
});
}
+(BOOL)dt_propertyIsOptional:(NSString *)propertyName{
[self dt_propertyIsOptional:propertyName];
return YES;
}
@end
网友评论