特别注意的是这个只能是字典,在model层中定义json数据中你需要的属性就好,但是属性名必须和json中的属性名(key)相同###
</br>
程序的入口是调用这个方法####
- (void)jsonWithSetAttributeForModelFromDictionnary: (NSDictionary *) dictionnaryOfJson
**建立映射关系:json数据中的key为关键字就改成类名+关键字,
如json数据中 key = id 那么model中设置属性不可能用model.id调用吧;所以改为类名+ID这样就能调用了 **
- (NSMutableDictionary *)relationShipBetweenModelAndJson:(NSDictionary *)dic {
//取出字典中所有的key
NSArray *keys = [dic allKeys];
NSMutableDictionary *newDic = [NSMutableDictionary dictionary];
/*
1.产生映射关系如title的set方法---->setTitle
2.创建一个可变字典将key(本身) :value(本身)如果为传过来的字典中有关键字则value变成类名加本身。如id ---->NSStringFromClass+id
3.返回
*/
for (NSString *keyStr in keys) {
if ([keyStr isEqualToString:@"id"]) {
NSString *classStr = NSStringFromClass([self class]);
NSString *newStr = [NSString stringWithFormat:@"%@Id",classStr];
[newDic setObject:newStr forKey:@"id"];
}
else if ([keyStr isEqualToString:@"release"]){
NSString *classStr = NSStringFromClass([self class]);
NSString *newStr = [NSString stringWithFormat:@"%@Release",classStr];
[newDic setObject:newStr forKey:@"release"];
}
else {
[newDic setObject:keyStr forKey:keyStr];
}
}
return newDic;
}
**映射好属性后可以为每个属性生成set方法
如:name ----------->setName: **
- (SEL)createSetMethodForValue :(NSString *)KeyName {
//截取第一个单词并大写
NSString *fisrtWord = [[KeyName substringToIndex:1]uppercaseString];
//截取剩余的字符
NSString *otherStr = [KeyName substringFromIndex:1];
//拼接
NSString *setterStr = [NSString stringWithFormat:@"set%@%@:",fisrtWord,otherStr];
//构建set方法
SEL setterMethod = NSSelectorFromString(setterStr);
return setterMethod;
}
将json数据中的value取出来然后为每个set方法赋值
- (void)jsonWithSetAttributeForModelFromDictionnary: (NSDictionary *) dictionnaryOfJson{
//获取构建好的映射字典
NSMutableDictionary *mDictionary = [self relationShipBetweenModelAndJson:dictionnaryOfJson];
NSArray *allKey = [mDictionary allKeys];
for (NSString *key in allKey) {
//获取新构建的key
NSString *popertyName = [mDictionary objectForKey:key];
//根据新构建的key建立set方法 如:rating--->setRating
SEL method = [self createSetMethodForValue:popertyName];
//获取原有字典中key的值
id value = [dictionnaryOfJson objectForKey:key];
//判断你在model中有没有设置这个属性,如果没有设置这个属性就不执行下面的方法
if ([self respondsToSelector:method]) {
//这里是为set方法赋值
[self performSelector:method withObject:value];
}
}
}