接口返回的key转成属性名
+ (NSDictionary*)lj_replacedKeyWithProperty {
return @{@"propertyName":@"key"};
}
model中嵌套子model
+ (NSDictionary*)lj_modelWithArrayObject {
return @{@"key":@"subModel"};
}
字典转模型
+ (instancetype)lj_modelWithDict:(NSDictionary*)dict {
id objc = [[self alloc] init];
unsigned int count = 0;
Ivar *ivar = class_copyIvarList(self, &count);
for(int i = 0; i < count; i ++) {
Ivar iva = ivar[i];
NSString *name = [NSString stringWithUTF8String:ivar_getName(iva)];
NSString *type = [NSString stringWithUTF8String:ivar_getTypeEncoding(iva)];
type = [type stringByReplacingOccurrencesOfString:@"\""withString:@""];
type = [type stringByReplacingOccurrencesOfString:@"@"withString:@""];
name = [name substringFromIndex:1];
NSString *key = [NSString stringWithString:name];
if([self respondsToSelector:@selector(lj_replacedKeyWithProperty)]) {
NSString *object = [[self lj_replacedKeyWithProperty] objectForKey:key];
if(object) {
key = object;
}
}
id value = dict[key];
if(!value) {
continue;
}
if([self respondsToSelector:@selector(lj_modelWithArrayObject)]) {
if([[[self lj_modelWithArrayObject] allKeys] containsObject:name]) {
NSString *object = [[self lj_modelWithArrayObject] valueForKey:name];
Class subClass = NSClassFromString(object);
if([value isKindOfClass:[NSDictionary class]]) {
value = [subClass lj_modelWithDict:value];
} else if ([value isKindOfClass:[NSArray class]]) {
NSMutableArray*array = [NSMutableArray new];
for(id subDict in value) {
id subObject = [subClass lj_modelWithDict:subDict];
[array addObject:subObject];
}
value = [NSArray arrayWithArray:array];
}
}
}
[objc setValue:value forKey:name];
}
return objc;
}