OC- Json 转 Model
2020-07-15 本文已影响0人
派大星的博客
@interface NSObject (JsonToModel)
- (void)parseJsonToModel:(NSDictionary *)dictionaryJson
@end
objc_getClass 和 class_copyPropertyList
// 获取对象
NSString *className = NSStringFromClass([self class]);
const char *cClassName = [className UTF8String];
id theClass = objc_getClass(cClassName);
// 获取 properties
unsigned int propertyCount;
objc_property_t *properties = class_copyPropertyList(theClass, &propertyCount);
// Loop in properties
for property in properties {
// 内部实现
}
Loop内部实现
// 获取 property_getName 和 property_getAttributes
NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
NSString *propertyType = [[NSString alloc] initWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding];
// 通过propertyName获取Var
Ivar iVar = class_getInstanceVariable([self class], [propertyName UTF8String]);
// 通过propertyName去Json中寻找Value
id jsonValue = [dictionaryJson objectForKey:propertyName];
Switch property_getAttributes
- case
NSString
object_setIvar(self, iVar, jsonValue);
- case
NSNumber
object_setIvar(self, iVar, jsonValue);
- case
NSDictionary
object_setIvar(self, iVar, jsonValue);
- case
NSArray
NSArray *arrayVarInfo = [propertyName componentsSeparatedByString:@"__Array__"];
if ([arrayVarInfo count] == 2)
{
NSString *keyValue = [arrayVarInfo objectAtIndex:0];
NSString *varClassName = [arrayVarInfo objectAtIndex:1];
jsonValue = [dictionaryJson objectForKey:keyValue];
NSMutableArray *arrayValue = [[NSMutableArray alloc] init];
// 内部递归 parseJsonToModel
[self parseJsonArray:jsonValue toArray: arrayValue forClassName:varClassName];
object_setIvar(self, iVar, arrayDest);
}
- case
customType
NSArray *arrayTypeInfo = [propertyType componentsSeparatedByString:@"\""];
if ([arrayTypeInfo count] > 2)
{
NSString *varClassName = [arrayTypeInfo objectAtIndex:1];
// 创建对象
Class varClass = NSClassFromString(varClassName);
if (varClass != nil)
{
id varObject = [[varClass alloc] init];
// 递归进行下层解析
[varObject parseJsonToModel:jsonValue];
object_setIvar(self, iVar, varObject);
}
}