一般情况下,Json转Model有两种方法:
1、手动转,也就是自己写model,然后通过将获取json里的字典,通过字段手动填值。
2、自己写model,然后通过运行oc的运行时库将json里的字典自动填充到model中。
方法1的缺点是无法实现智能化,每个json数据都需要逐个填充,方法2就解决了这个问题。
比如说我有这样的json数据(json已经转为字典类型):
NSDictionary *dataDic =@{@"name":@"trump",@"age":@"60",@"avatar":@"www.baidu.com"};
一、Model:
@interface Model : NSObject
@property (nonatomic,copy)NSString *name;
@property (nonatomic,assign)NSInteger age;
@property (nonatomic,strong)NSDictionary *avatar;
@end
只要通过
Mode *model = [selfmodelWithDict:dataDicmodelClass:@"Model"];
就可以就生成模型了,以后有其他的json,只要根据json数据的字段定义Model,然后在调用一次modelWithDict就解析好json并获取Model了。
二、dic转Model:
+ (id)modelWithDict:(NSDictionary *)dict modelClass:(NSString *)className {
if (dict == nil || className ==nil || className.length ==0) {
return nil;
}
//取得类对象
Class ModelClass = objc_getClass([classNameUTF8String]);
//NSClassFromString: 判断是否存在字符串对应的类:返回类名或nil
id model = [[ModelClass alloc] init];
unsigned int propertiesCount =0;
unsigned int ivarsCount =0;
//class_copyPropertyList解析见博文:class_copyPropertyList和class_copyIvarList的区别
objc_property_t *properties = class_copyPropertyList(ModelClass, &propertiesCount);
Ivar *ivars = class_copyIvarList(ModelClass, &ivarsCount);
for(int i =0; i < ivarsCount; i++) {
NSString *memberName = [NSStringstringWithUTF8String:ivar_getName(ivars[i])];
for (int j =0; j < propertiesCount; j++) {
NSString *propertyName = [[NSStringalloc]initWithCString:property_getName(properties[j])encoding:NSUTF8StringEncoding];
NSRange range = [memberName rangeOfString:propertyName];
if (range.location ==NSNotFound) {
continue;
}
else {
id propertyValue = [dict objectForKey:propertyName];
if (!propertyValue) {
NSLog(@"json中'%@'字段不存在或数据为NULL", propertyName);
continue;
}
[model setValue:propertyValue forKey:memberName];
}
}
}
return model;
}
扩展:github其实早就有这样的第三方组件,并且功能强大,比如:JsonModel(https://github.com/icanzilb/JSONModel/), 上面的代码只是个雏形,虽然没看过jsonmodel的源码,但我猜也因该是通过oc的运行时来实现的。