【iOS】——JSONModel源码

打印 上一主题 下一主题

主题 1032|帖子 1032|积分 3096

JSONModel用法

根本用法

将传入的字典转换成模型:
起首定义模型类:
  1. @interface Person : JSONModel
  2. @property (nonatomic, copy)   NSString *name;
  3. @property (nonatomic, copy)   NSString *sex;
  4. @property (nonatomic, assign) NSInteger age;
  5. @end
复制代码
接着使用字典来转换为模型:
  1. NSDictionary *dict = @{
  2.                         @"name":@"Jack",
  3.                         @"age":@23,
  4.                         @"gender":@"male",
  5.                       };
  6. NSError *error;
  7. Person *person = [[Person alloc] initWithDictionary:dict error:&error];
复制代码
转换属性名称

有时间传入的字典的key名和J模型类的属性名称不匹配, 比如字典的key名被修改,从而导致非常,因此必要keyPapper方法来将模型中的属性转换成字典中对应的key名。
keyMapper方法必要返回一个字典,该字典的key是模型类的属性名称,value是传入的字典的key名
比如修改一下传入的字典里的gender字段为sex:
  1. @implementation Person
  2. + (JSONKeyMapper *)keyMapper
  3. {
  4.     return [[JSONKeyMapper alloc] initWithModelToJSONDictionary:@{
  5.                                                                   @"gender": @"sex",                                                             }];
  6. }
复制代码
这样一来,JSONKeyMapper就会自动帮我们做转换
自定义错误

JSONModel框架的作者答应开发者自定义错误阻止模型的转换
使用validate方法
比如实现当age对应的数值小于18等待时间输出未成年,并阻止模型的转换:
  1. - (BOOL)validate:(NSError **)error
  2. {
  3.     if (![super validate:error])
  4.         return NO;
  5.    
  6.     if (self.age < 18)
  7.     {
  8.         *error = [NSError errorWithDomain:@"未成年!" code:10 userInfo:nil];
  9.         NSError *errorLog = *error;
  10.         NSLog(@"%@",errorLog.domain);
  11.         return NO;
  12.     }
  13.    
  14.     return YES;
  15. }
复制代码
模型嵌套

源码分析


在JSONMoodel中提供了四种初始化方法:
  1. -(instancetype)initWithString:(NSString*)string error:(JSONModelError**)err;
  2. -(instancetype)initWithString:(NSString *)string usingEncoding:(NSStringEncoding)encoding error:(JSONModelError**)err;
  3. -(instancetype)initWithDictionary:(NSDictionary*)dict error:(NSError **)err;
  4. -(instancetype)initWithData:(NSData *)data error:(NSError **)error;
复制代码
这些初始化方法终极都会调用initWithDictionary方法
  1. -(instancetype)initWithData:(NSData *)data error:(NSError *__autoreleasing *)err
  2. {
  3.     //check for nil input
  4.     if (!data) {
  5.         if (err) *err = [JSONModelError errorInputIsNil];
  6.         return nil;
  7.     }
  8.     //read the json
  9.     JSONModelError* initError = nil;
  10.     id obj = [NSJSONSerialization JSONObjectWithData:data
  11.                                              options:kNilOptions
  12.                                                error:&initError];
  13.     if (initError) {
  14.         if (err) *err = [JSONModelError errorBadJSON];
  15.         return nil;
  16.     }
  17.     //init with dictionary
  18.     id objModel = [self initWithDictionary:obj error:&initError];
  19.     if (initError && err) *err = initError;
  20.     return objModel;
  21. }
  22. -(id)initWithString:(NSString*)string error:(JSONModelError**)err
  23. {
  24.     JSONModelError* initError = nil;
  25.     id objModel = [self initWithString:string usingEncoding:NSUTF8StringEncoding error:&initError];
  26.     if (initError && err) *err = initError;
  27.     return objModel;
  28. }
  29. -(id)initWithString:(NSString *)string usingEncoding:(NSStringEncoding)encoding error:(JSONModelError**)err
  30. {
  31.     //check for nil input
  32.     if (!string) {
  33.         if (err) *err = [JSONModelError errorInputIsNil];
  34.         return nil;
  35.     }
  36.     JSONModelError* initError = nil;
  37.     id objModel = [self initWithData:[string dataUsingEncoding:encoding] error:&initError];
  38.     if (initError && err) *err = initError;
  39.     return objModel;
  40. }
复制代码
下面是initWithDictionary:的源码:
几个紧张的点


  • 关联对象kClassPropertiesKey用来保存所有属性信息的NSDictionary)
  • 关联对象kClassRequiredPropertyNamesKey用来保存所有属性的名称的NSSet)
  • 关联对象kMapperObjectKey用来保存JSONKeyMapper):自定义的mapper,详细的方法就是用来自定义修改担当数据中的key
  • JSONModelClassProperty:封装的jsonmodel的一个属性,它包含了对应属性的名字:(例如 name:gender),范例(例如 type:NSString),是否是JSONModel支持的范例(isStandardJSONType:YES/NO),是否是可变对象(isMutable:YES/NO)等属性。
整个执行流程: 起首,在这个模型类的对象被初始化的时间,遍历自身到所有的父类(直到JSONModel为止),获取所有的属性,并将其保存在一个字典里。获取传入字典的所有key,将这些key与保存的所有属性进行匹配。假如匹配成功,则进行kvc赋值。
initWithDictionary

  1. //这个方法里包含了作者做到的所有的容错和模型转化
  2. -(id)initWithDictionary:(NSDictionary*)dict error:(NSError**)err
  3. {
  4.     //check for nil input
  5.     //1.第一步判断传入的是否为nil
  6.     if (!dict) {
  7.         if (err) *err = [JSONModelError errorInputIsNil];
  8.         return nil;
  9.     }
  10.     //invalid input, just create empty instance
  11.     //2.第二步判断传入的是否为字典类型
  12.     if (![dict isKindOfClass:[NSDictionary class]]) {
  13.         if (err) *err = [JSONModelError errorInvalidDataWithMessage:@"Attempt to initialize JSONModel object using initWithDictionary:error: but the dictionary parameter was not an 'NSDictionary'."];
  14.         return nil;
  15.     }
  16.     //create a class instance
  17.     //3.创建类实例,通过init方法初始化映射property
  18.     self = [self init];
  19.     if (!self) {
  20.         //super init didn't succeed
  21.         if (err) *err = [JSONModelError errorModelIsInvalid];
  22.         return nil;
  23.     }
  24.     //check incoming data structure
  25.     //4.检查用户定义的模型里的属性集合是否大于传入的字典里的key集合(如果大于,则返回NO)就返回nil,并且抛出错误
  26.     if (![self __doesDictionary:dict matchModelWithKeyMapper:self.__keyMapper error:err]) {
  27.         return nil;
  28.     }
  29.     //import the data from a dictionary
  30.     //5.根据传入的dict进行数据的赋值,如果赋值没有成功,就返回nil,并且抛出错误。
  31.     if (![self __importDictionary:dict withKeyMapper:self.__keyMapper validation:YES error:err]) {
  32.         return nil;
  33.     }
  34.     //run any custom model validation
  35.     //6.根据本地的错误来判断是否有错误,如果有错误,就返回nil,并且抛出错误。
  36.     if (![self validate:err]) {
  37.         return nil;
  38.     }
  39.     //model is valid! yay!
  40.     //7.前面的判断都通过,返回self
  41.     return self;
  42. }
复制代码


  • 判断传入的参数是否为空,假如为空直接返回nii
  • 查抄参数是否是NSDictonary的实例,假如不是返回nil
  • 初始化JSONModel实例,设置Model1的属性集合
  • 查抄Model类的属性数量是否大于传入的的字典的key的数量,假如大于则返回NO
  • 将传入的dict的值赋值给Model类的属性
  • 假如重写了validate方法,则根据自定义的错误来阻拦model的返回
init

  1. - (id)init
  2. {
  3.     self = [super init];
  4.     if (self) {
  5.         //do initial class setup
  6.         [self __setup__];
  7.     }
  8.     return self;
  9. }
复制代码
在该方法中调用了setup方法
setup

  1. - (void)__setup__
  2. {
  3.     //if first instance of this model, generate the property list
  4.     // 如果是该模型的第一个实例,则生成属性列表
  5.     if (!objc_getAssociatedObject(self.class, &kClassPropertiesKey)) {
  6.         [self __inspectProperties];
  7.     }
  8.     //if there's a custom key mapper, store it in the associated object
  9.     id mapper = [[self class] keyMapper];
  10.     if ( mapper && !objc_getAssociatedObject(self.class, &kMapperObjectKey) ) {
  11.         objc_setAssociatedObject(
  12.                                  self.class,
  13.                                  &kMapperObjectKey,
  14.                                  mapper,
  15.                                  OBJC_ASSOCIATION_RETAIN // This is atomic
  16.                                  );
  17.     }
  18. }
复制代码


  • 起首通过objc_getAssociatedObject方法判断属性是否已经被缓存过,假如没有就调用inspectProperties方法将属性进行缓存
  • 接着判断是否存在keyMapper方法,假如有就将keyMapper与模型类进行关联
__inspectProperties

  1. -(void)__inspectProperties
  2. {
  3. //    最终保存所有属性的字典,形式为:
  4. //    {
  5. //        age = "@property primitive age (Setters = [])";
  6. //        friends = "@property NSArray* friends (Standard JSON type, Setters = [])";
  7. //        gender = "@property NSString* gender (Standard JSON type, Setters = [])";
  8. //        name = "@property NSString* name (Standard JSON type, Setters = [])";
  9. //    }
  10.     NSMutableDictionary* propertyIndex = [NSMutableDictionary dictionary];
  11.     //获取当前的类名
  12.     Class class = [self class];   
  13.     NSScanner* scanner = nil;
  14.     NSString* propertyType = nil;
  15.     // 循环条件:当class 是 JSONModel自己的时候终止
  16.     while (class != [JSONModel class]) {        
  17.         //属性的个数
  18.         unsigned int propertyCount;
  19.         //获得属性列表(所有@property声明的属性)
  20.         objc_property_t *properties = class_copyPropertyList(class, &propertyCount);
  21.         //遍历所有的属性
  22.         for (unsigned int i = 0; i < propertyCount; i++) {
  23.             //获得属性名称
  24.             objc_property_t property = properties[i];//获得当前的属性
  25.             const char *propertyName = property_getName(property);//name(C字符串)            
  26.             //JSONModel里的每一个属性,都被封装成一个JSONModelClassProperty对象
  27.             JSONModelClassProperty* p = [[JSONModelClassProperty alloc] init];
  28.             p.name = @(propertyName);//propertyName:属性名称,例如:name,age,gender
  29.             //获得属性类型
  30.             const char *attrs = property_getAttributes(property);
  31.             NSString* propertyAttributes = @(attrs);
  32.             // T@"NSString",C,N,V_name
  33.             // Tq,N,V_age
  34.             // T@"NSString",C,N,V_gender
  35.             // T@"NSArray",&,N,V_friends            
  36.             NSArray* attributeItems = [propertyAttributes componentsSeparatedByString:@","];
  37.             //说明是只读属性,不做任何操作
  38.             if ([attributeItems containsObject:@"R"]) {
  39.                 continue; //to next property
  40.             }
  41.             //检查出是布尔值
  42.             if ([propertyAttributes hasPrefix:@"Tc,"]) {
  43.                 p.structName = @"BOOL";//使其变为结构体
  44.             }            
  45.             //实例化一个scanner
  46.             scanner = [NSScanner scannerWithString: propertyAttributes];
  47.             [scanner scanUpToString:@"T" intoString: nil];
  48.             [scanner scanString:@"T" intoString:nil];
  49.             //http://blog.csdn.net/kmyhy/article/details/8258858           
  50.             if ([scanner scanString:@"@"" intoString: &propertyType]) {               
  51.                  //属性是一个对象
  52.                 [scanner scanUpToCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:@""<"]
  53.                                         intoString:&propertyType];//propertyType -> NSString               
  54.                 p.type = NSClassFromString(propertyType);// p.type = @"NSString"
  55.                 p.isMutable = ([propertyType rangeOfString:@"Mutable"].location != NSNotFound); //判断是否是可变的对象
  56.                 p.isStandardJSONType = [allowedJSONTypes containsObject:p.type];//是否是该框架兼容的类型
  57.                 //存在协议(数组,也就是嵌套模型)
  58.                 while ([scanner scanString:@"<" intoString:NULL]) {
  59.                     NSString* protocolName = nil;
  60.                     [scanner scanUpToString:@">" intoString: &protocolName];
  61.                     if ([protocolName isEqualToString:@"Optional"]) {
  62.                         p.isOptional = YES;
  63.                     } else if([protocolName isEqualToString:@"Index"]) {
  64. #pragma GCC diagnostic push
  65. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  66.                         p.isIndex = YES;
  67. #pragma GCC diagnostic pop
  68.                         objc_setAssociatedObject(
  69.                                                  self.class,
  70.                                                  &kIndexPropertyNameKey,
  71.                                                  p.name,
  72.                                                  OBJC_ASSOCIATION_RETAIN // This is atomic
  73.                                                  );
  74.                     } else if([protocolName isEqualToString:@"Ignore"]) {
  75.                         p = nil;
  76.                     } else {
  77.                         p.protocol = protocolName;
  78.                     }
  79.                     //到最接近的>为止
  80.                     [scanner scanString:@">" intoString:NULL];
  81.                 }
  82.             }            
  83.             else if ([scanner scanString:@"{" intoString: &propertyType])               
  84.                 //属性是结构体
  85.                 [scanner scanCharactersFromSet:[NSCharacterSet alphanumericCharacterSet]
  86.                                     intoString:&propertyType];
  87.                 p.isStandardJSONType = NO;
  88.                 p.structName = propertyType;
  89.             }
  90.             else {
  91.                 //属性是基本类型:Tq,N,V_age
  92.                 [scanner scanUpToCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:@","]
  93.                                         intoString:&propertyType];
  94.                 //propertyType:q
  95.                 propertyType = valueTransformer.primitivesNames[propertyType];              
  96.                 //propertyType:long
  97.                 //基本类型数组
  98.                 if (![allowedPrimitiveTypes containsObject:propertyType]) {
  99.                     //类型不支持
  100.                     @throw [NSException exceptionWithName:@"JSONModelProperty type not allowed"
  101.                                                    reason:[NSString stringWithFormat:@"Property type of %@.%@ is not supported by JSONModel.", self.class, p.name]
  102.                                                  userInfo:nil];
  103.                 }
  104.             }
  105.             NSString *nsPropertyName = @(propertyName);            
  106.             //可选的
  107.             if([[self class] propertyIsOptional:nsPropertyName]){
  108.                 p.isOptional = YES;
  109.             }
  110.             //可忽略的
  111.             if([[self class] propertyIsIgnored:nsPropertyName]){
  112.                 p = nil;
  113.             }
  114.             //集合类
  115.             Class customClass = [[self class] classForCollectionProperty:nsPropertyName];            
  116.             if (customClass) {
  117.                 p.protocol = NSStringFromClass(customClass);
  118.             }
  119.             //忽略block
  120.             if ([propertyType isEqualToString:@"Block"]) {
  121.                 p = nil;
  122.             }
  123.             //如果字典里不存在,则添加到属性字典里(终于添加上去了。。。)
  124.             if (p && ![propertyIndex objectForKey:p.name]) {
  125.                 [propertyIndex setValue:p forKey:p.name];
  126.             }
  127.             //setter 和 getter
  128.             if (p)
  129.             {   //name ->Name
  130.                 NSString *name = [p.name stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:[p.name substringToIndex:1].uppercaseString];
  131.                 // getter
  132.                 SEL getter = NSSelectorFromString([NSString stringWithFormat:@"JSONObjectFor%@", name]);
  133.                 if ([self respondsToSelector:getter])
  134.                     p.customGetter = getter;
  135.                 // setters
  136.                 p.customSetters = [NSMutableDictionary new];
  137.                 SEL genericSetter = NSSelectorFromString([NSString stringWithFormat:@"set%@WithJSONObject:", name]);
  138.                 if ([self respondsToSelector:genericSetter])
  139.                     p.customSetters[@"generic"] = [NSValue valueWithBytes:&genericSetter objCType:@encode(SEL)];
  140.                 for (Class type in allowedJSONTypes)
  141.                 {
  142.                     NSString *class = NSStringFromClass([JSONValueTransformer classByResolvingClusterClasses:type]);
  143.                     if (p.customSetters[class])
  144.                         continue;
  145.                     SEL setter = NSSelectorFromString([NSString stringWithFormat:@"set%@With%@:", name, class]);
  146.                     if ([self respondsToSelector:setter])
  147.                         p.customSetters[class] = [NSValue valueWithBytes:&setter objCType:@encode(SEL)];
  148.                 }
  149.             }
  150.         }
  151.         free(properties);
  152.         //再指向自己的父类,知道等于JSONModel才停止
  153.         class = [class superclass];
  154.     }
  155.     //最后保存所有当前类,JSONModel的所有的父类的属性
  156.     objc_setAssociatedObject(
  157.                              self.class,
  158.                              &kClassPropertiesKey,
  159.                              [propertyIndex copy],
  160.                              OBJC_ASSOCIATION_RETAIN
  161.                              );
  162. }
复制代码


  • 起首进入循环,循环终止的条件是当前类是JSONModel类。
  • 接着使用 class_copyPropertyList方法获取Model类的属性列表
  • 然后为每个属性创建一个JSONModelProperty对象
  • JSONModelProperty对象是创建的propertyIndex的value值
  • JSONModelProperty 对象中包含了属性名、数据范例、对应的 JSON 字段名等信息
  • 将当前类的指针指向其父类
  • 最后所有的这些 JSONModelProperty 对象都会存储在一个NSMutableDictionary 对象——propertyIndex中,然后通过objc_setAssociatedObject与模型进行关联
这个方法用于检索JSONModel类中的属性,并将其转化为一个可用的 NSDictionary 对象。该方法会遍历模型类的属性,然后解析每个属性的相干信息(如属性名、数据范例、对应的 JSON 字段名等),并将其存储在 NSDictionary 对象中,也就是上文的propertyIndex
- (BOOL)__doesDictionaryNSDictionary*)dict matchModelWithKeyMapperJSONKeyMapper*)keyMapper

  1. //model类里面定义的属性集合是不能大于传入的字典里的key集合的。
  2. //如果存在了用户自定义的mapper,则需要按照用户的定义来进行转换。
  3. //(例如将gender转换为了sex)。
  4. -(BOOL)__doesDictionary:(NSDictionary*)dict matchModelWithKeyMapper:(JSONKeyMapper*)keyMapper error:(NSError**)err
  5. {
  6.     //check if all required properties are present
  7.     //拿到字典里所有的key
  8.     NSArray* incomingKeysArray = [dict allKeys];
  9.     NSMutableSet* requiredProperties = [self __requiredPropertyNames].mutableCopy;
  10.     //从array拿到set
  11.     NSSet* incomingKeys = [NSSet setWithArray: incomingKeysArray];
  12.     //transform the key names, if necessary
  13.     //如有必要,变换键名称
  14.     //如果用户自定义了mapper,则进行转换
  15.     if (keyMapper || globalKeyMapper) {
  16.         NSMutableSet* transformedIncomingKeys = [NSMutableSet setWithCapacity: requiredProperties.count];
  17.         NSString* transformedName = nil;
  18.         //loop over the required properties list
  19.         //在所需属性列表上循环
  20.         //遍历需要转换的属性列表
  21.         for (JSONModelClassProperty* property in [self __properties__]) {
  22.             //被转换成的属性名称(例如)TestModel(模型内) -> url(字典内)
  23.             transformedName = (keyMapper||globalKeyMapper) ? [self __mapString:property.name withKeyMapper:keyMapper] : property.name;
  24.             //check if exists and if so, add to incoming keys
  25.             //检查是否存在,如果存在,则添加到传入密钥
  26.             //(例如)拿到url以后,查看传入的字典里是否有url对应的值
  27.             id value;
  28.             @try {
  29.                 value = [dict valueForKeyPath:transformedName];
  30.             }
  31.             @catch (NSException *exception) {
  32.                 value = dict[transformedName];
  33.             }
  34.             if (value) {
  35.                 [transformedIncomingKeys addObject: property.name];
  36.             }
  37.         }
  38.         //overwrite the raw incoming list with the mapped key names
  39.         //用映射的键名称覆盖原始传入列表
  40.         incomingKeys = transformedIncomingKeys;
  41.     }
  42.     //check for missing input keys
  43.     //检查是否缺少输入键
  44.     //查看当前的model的属性的集合是否大于传入的属性集合,如果是,则返回错误
  45.     //也就是说模型类里的属性是不能多于传入字典里的key的,例如:
  46.     if (![requiredProperties isSubsetOfSet:incomingKeys]) {
  47.         //get a list of the missing properties
  48.         //获取缺失属性的列表(获取多出来的属性)
  49.         [requiredProperties minusSet:incomingKeys];
  50.         //not all required properties are in - invalid input
  51.         //并非所有必需的属性都在 in - 输入无效
  52.         JMLog(@"Incoming data was invalid [%@ initWithDictionary:]. Keys missing: %@", self.class, requiredProperties);
  53.         if (err) *err = [JSONModelError errorInvalidDataWithMissingKeys:requiredProperties];
  54.         return NO;
  55.     }
  56.     //not needed anymore
  57.     //不再需要了,释放掉
  58.     incomingKeys= nil;
  59.     requiredProperties= nil;
  60.     return YES;
  61. }
复制代码


  • 起首获取dict中所有的key名传入数组incomingKeysArray中
  • 接着获取Model类中所有的属性名传入集合equiredProperties中
  • 将dict中得到的key数组转换为集合范例
  • 假如存在keyMapper大概globalKeyMapper则将模型中的属性名转换为KeyMapper中对应的Value,也就是将Model类中的属性名转换为Json数据key名
  • 更新dict的键名集合,这样做是为了包管dict中的每个键名都有对应的有效值,而不是仅仅只有一个key键
  • 查抄Model类的属性数量是否大于传入的的字典的key的数量,假如大于则返回NO,因为此时JSON中的数据不能完全覆盖我们声明的属性
- (BOOL)__importDictionaryNSDictionary*)dict withKeyMapperJSONKeyMapper*)keyMapper validationBOOL)validation errorNSError**)err

使用kvc根据传入的dict进行数据的赋值,假如赋值没有成功,就返回nil,而且抛堕落误。
  1. //作者在最后给属性赋值的时候使用的是kvc的setValue:ForKey:的方法。
  2. //作者判断了模型里的属性的类型是否是JSONModel的子类,可见作者的考虑是非常周全的。
  3. //整个框架看下来,有很多的地方涉及到了错误判断,作者将将错误类型单独抽出一个类(JSONModelError),里面支持的错误类型很多,可以侧面反应作者思维之缜密。而且这个做法也可以在我们写自己的框架或者项目中使用。
  4. //从字典里获取值并赋给当前模型对象
  5. -(BOOL)__importDictionary:(NSDictionary*)dict withKeyMapper:(JSONKeyMapper*)keyMapper validation:(BOOL)validation error:(NSError**)err
  6. {
  7.     //loop over the incoming keys and set self's properties
  8.     //遍历保存的所有属性的字典
  9.     for (JSONModelClassProperty* property in [self __properties__]) {
  10.         //convert key name to model keys, if a mapper is provided
  11.         //将属性的名称(若有改动就拿改后的名称)拿过来,作为key,用这个key来查找传进来的字典里对应的值
  12.         NSString* jsonKeyPath = (keyMapper||globalKeyMapper) ? [self __mapString:property.name withKeyMapper:keyMapper] : property.name;
  13.         //JMLog(@"keyPath: %@", jsonKeyPath);
  14.         //general check for data type compliance
  15.         //用来保存从字典里获取的值
  16.         id jsonValue;
  17.         @try {
  18.             jsonValue = [dict valueForKeyPath: jsonKeyPath];
  19.         }
  20.         @catch (NSException *exception) {
  21.             jsonValue = dict[jsonKeyPath];
  22.         }
  23.         //check for Optional properties
  24.         //检查可选属性
  25.         //字典不存在对应的key
  26.         if (isNull(jsonValue)) {
  27.             //skip this property, continue with next property
  28.             //跳过此属性,继续下一个属性
  29.             //如果这个key是可以不存在的
  30.             if (property.isOptional || !validation) continue;
  31.             //如果这个key是必须有的,则返回错误
  32.             if (err) {
  33.                 //null value for required property
  34.                 //所需属性的值为null
  35.                 NSString* msg = [NSString stringWithFormat:@"Value of required model key %@ is null", property.name];
  36.                 JSONModelError* dataErr = [JSONModelError errorInvalidDataWithMessage:msg];
  37.                 *err = [dataErr errorByPrependingKeyPathComponent:property.name];
  38.             }
  39.             return NO;
  40.         }
  41.         //获取,取到的值的类型
  42.         Class jsonValueClass = [jsonValue class];
  43.         BOOL isValueOfAllowedType = NO;
  44.         //查看是否是本框架兼容的属性类型
  45.         for (Class allowedType in allowedJSONTypes) {
  46.             if ( [jsonValueClass isSubclassOfClass: allowedType] ) {
  47.                 isValueOfAllowedType = YES;
  48.                 break;
  49.             }
  50.         }
  51.         
  52.         //如果不兼容,则返回NO,mapping失败,抛出错误
  53.         if (isValueOfAllowedType==NO) {
  54.             //type not allowed
  55.             JMLog(@"Type %@ is not allowed in JSON.", NSStringFromClass(jsonValueClass));
  56.             if (err) {
  57.                 NSString* msg = [NSString stringWithFormat:@"Type %@ is not allowed in JSON.", NSStringFromClass(jsonValueClass)];
  58.                 JSONModelError* dataErr = [JSONModelError errorInvalidDataWithMessage:msg];
  59.                 *err = [dataErr errorByPrependingKeyPathComponent:property.name];
  60.             }
  61.             return NO;
  62.         }
  63.         //check if there's matching property in the model
  64.         //检查模型中是否有匹配的属性
  65.         //如果是兼容的类型:
  66.         if (property) {
  67.             // check for custom setter, than the model doesn't need to do any guessing
  68.             // how to read the property's value from JSON
  69.             //检查自定义setter,则模型不需要进行任何猜测(查看是否有自定义setter,并设置)
  70.             //如何从JSON读取属性值
  71.             if ([self __customSetValue:jsonValue forProperty:property]) {
  72.                 //skip to next JSON key
  73.                 //跳到下一个JSON键
  74.                 continue;
  75.             };
  76.             // 0) handle primitives
  77.             if (property.type == nil && property.structName==nil) {
  78.                 //generic setter
  79.                 //通用setter
  80.                 //kvc赋值
  81.                 if (jsonValue != [self valueForKey:property.name]) {
  82.                     [self setValue:jsonValue forKey: property.name];
  83.                 }
  84.                 //skip directly to the next key
  85.                 //直接跳到下一个键
  86.                 continue;
  87.             }
  88.             // 0.5) handle nils
  89.             //如果传来的值是空,即使当前的属性对应的值不是空,也要将空值赋给它
  90.             if (isNull(jsonValue)) {
  91.                 if ([self valueForKey:property.name] != nil) {
  92.                     [self setValue:nil forKey: property.name];
  93.                 }
  94.                 continue;
  95.             }
  96.             // 1) check if property is itself a JSONModel
  97.             //检查属性本身是否是jsonmodel类型
  98.             if ([self __isJSONModelSubClass:property.type]) {
  99.                 //initialize the property's model, store it
  100.                 //初始化属性的模型,并将其存储
  101.                 //通过自身的转模型方法,获取对应的值
  102.                 JSONModelError* initErr = nil;
  103.                 id value = [[property.type alloc] initWithDictionary: jsonValue error:&initErr];
  104.                 if (!value) {
  105.                     //skip this property, continue with next property
  106.                     //跳过此属性,继续下一个属性(如果该属性不是必须的,则略过)
  107.                     if (property.isOptional || !validation) continue;
  108.                     // Propagate the error, including the property name as the key-path component
  109.                     //传播错误,包括将属性名称作为密钥路径组件(如果该属性是必须的,则返回错误)
  110.                     if((err != nil) && (initErr != nil))
  111.                     {
  112.                         *err = [initErr errorByPrependingKeyPathComponent:property.name];
  113.                     }
  114.                     return NO;
  115.                 }
  116.                 //当前的属性值与value不同时,则赋值
  117.                 if (![value isEqual:[self valueForKey:property.name]]) {
  118.                     [self setValue:value forKey: property.name];
  119.                 }
  120.                 //for clarity, does the same without continue
  121.                 //为清楚起见,不继续执行相同操作
  122.                 continue;
  123.             } else {
  124.                 // 2) check if there's a protocol to the property
  125.                 //  ) might or not be the case there's a built in transform for it
  126.                 //2)检查是否有协议
  127.                 //)可能是,也可能不是,它有一个内置的转换
  128.                 if (property.protocol) {
  129.                     //JMLog(@"proto: %@", p.protocol);
  130.                     //转化为数组,这个数组就是例子中的friends属性
  131.                     jsonValue = [self __transform:jsonValue forProperty:property error:err];
  132.                     if (!jsonValue) {
  133.                         if ((err != nil) && (*err == nil)) {
  134.                             NSString* msg = [NSString stringWithFormat:@"Failed to transform value, but no error was set during transformation. (%@)", property];
  135.                             JSONModelError* dataErr = [JSONModelError errorInvalidDataWithMessage:msg];
  136.                             *err = [dataErr errorByPrependingKeyPathComponent:property.name];
  137.                         }
  138.                         return NO;
  139.                     }
  140.                 }
  141.                 // 3.1) handle matching standard JSON types
  142.                 //3.1)句柄匹配标准JSON类型
  143.                 //对象类型
  144.                 if (property.isStandardJSONType && [jsonValue isKindOfClass: property.type]) {
  145.                     //mutable properties
  146.                     //可变类型的属性
  147.                     if (property.isMutable) {
  148.                         jsonValue = [jsonValue mutableCopy];
  149.                     }
  150.                     //set the property value
  151.                     //为属性赋值
  152.                     if (![jsonValue isEqual:[self valueForKey:property.name]]) {
  153.                         [self setValue:jsonValue forKey: property.name];
  154.                     }
  155.                     continue;
  156.                 }
  157.                 // 3.3) handle values to transform
  158.                 //3.3)处理要转换的值
  159.                 //当前的值的类型与对应的属性的类型不一样的时候,需要查看用户是否自定义了转换器(例如从NSSet到NSArray转换:-(NSSet *)NSSetFromNSArray:(NSArray *)array)
  160.    
  161.                 if (
  162.                     (![jsonValue isKindOfClass:property.type] && !isNull(jsonValue))
  163.                     ||
  164.                     //the property is mutable
  165.                     //属性是可变的
  166.                     property.isMutable
  167.                     ||
  168.                     //custom struct property
  169.                     //自定义结构属性
  170.                     property.structName
  171.                     ) {
  172.                     // searched around the web how to do this better
  173.                     // but did not find any solution, maybe that's the best idea? (hardly)
  174.                     //在网上搜索如何更好地做到这一点
  175.                     //但是没有找到任何解决方案,也许这是最好的主意?(几乎没有)
  176.                     Class sourceClass = [JSONValueTransformer classByResolvingClusterClasses:[jsonValue class]];
  177.                     //JMLog(@"to type: [%@] from type: [%@] transformer: [%@]", p.type, sourceClass, selectorName);
  178.                     //build a method selector for the property and json object classes
  179.                     //为属性和json对象类构建方法选择器
  180.                     NSString* selectorName = [NSString stringWithFormat:@"%@From%@:",
  181.                                               (property.structName? property.structName : property.type), //target name
  182.                                               sourceClass]; //source name
  183.                     SEL selector = NSSelectorFromString(selectorName);
  184.                     //check for custom transformer
  185.                     //查看自定义的转换器是否存在
  186.                     BOOL foundCustomTransformer = NO;
  187.                     if ([valueTransformer respondsToSelector:selector]) {
  188.                         foundCustomTransformer = YES;
  189.                     } else {
  190.                         //try for hidden custom transformer
  191.                         //尝试隐藏自定义转换器
  192.                         selectorName = [NSString stringWithFormat:@"__%@",selectorName];
  193.                         selector = NSSelectorFromString(selectorName);
  194.                         if ([valueTransformer respondsToSelector:selector]) {
  195.                             foundCustomTransformer = YES;
  196.                         }
  197.                     }
  198.                     //check if there's a transformer with that name
  199.                     //检查是否有同名变压器
  200.                     //如果存在自定义转换器,则进行转换
  201.                     if (foundCustomTransformer) {
  202.                         IMP imp = [valueTransformer methodForSelector:selector];
  203.                         id (*func)(id, SEL, id) = (void *)imp;
  204.                         jsonValue = func(valueTransformer, selector, jsonValue);
  205.                         if (![jsonValue isEqual:[self valueForKey:property.name]])
  206.                             [self setValue:jsonValue forKey:property.name];
  207.                     } else {
  208.                         //如果没有自定义转换器,返回错误
  209.                         if (err) {
  210.                             NSString* msg = [NSString stringWithFormat:@"%@ type not supported for %@.%@", property.type, [self class], property.name];
  211.                             JSONModelError* dataErr = [JSONModelError errorInvalidDataWithTypeMismatch:msg];
  212.                             *err = [dataErr errorByPrependingKeyPathComponent:property.name];
  213.                         }
  214.                         return NO;
  215.                     }
  216.                 } else {
  217.                     // 3.4) handle "all other" cases (if any)
  218.                     // 3.4) handle "all other" cases (if any)
  219.                     //3.4)处理“所有其他”情况(如有)
  220.                     if (![jsonValue isEqual:[self valueForKey:property.name]])
  221.                         [self setValue:jsonValue forKey:property.name];
  222.                 }
  223.             }
  224.         }
  225.     }
  226.     return YES;
  227. }
复制代码


  • 起首遍历模型类中的每个属性
  • 接着从JSON数据中拿出真正对应property的value,进行value一系列的值判断
  • value可用的情况下,就开始进行赋值,有setter方法的通过setter方法赋值,底子范例int,float等直接赋值
  • 假如property又是一个JSONModel,就递归先将子Model进行整体解析。
  • 假如包含protocol字段,则表明内部是一个array大概dictionary,并包含这个protocol字段的对象解析。
  • 对于其他情况,应该是一种范例的转换,通过获取值范例和property范例,调用相应的转换方法进行赋值。
   

  • 作者在最后给属性赋值的时间使用的是kvc的setValue:ForKey:的方法。
  • 作者判断了模型里的属性的范例是否是JSONModel的子类
  • 整个框架看下来,有很多的地方涉及到了错误判断,作者将将错误范例单独抽出一个类(JSONModelError),内里支持的错误范例很多,体现了作者头脑的缜密。而且这个做法也可以在我们写自己的框架大概项目中使用
  总结

通过获取Model类的属性列表,与传入的JSON数据自动匹配,同时还可以通过KeyMapper修改不相同的映射,假如模型类与JSON数据字段不匹配则会抛堕落误(这里体现为Model中某些必须的属性没有在JSON数据中找到相应的映射),最后假如范例等都查抄成功,则通过KVC将JSON数据中的value设置在Model类的对应的属性上


  • Runtime中动态解析Model数据范例,可以实现自动匹配
  • 已经解析过的Model1的属性列表会通过AssociatedObject进行缓存制止重复解析

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

河曲智叟

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表