iOS手动打造JSON Model转换库

移动开发 iOS
前一段时间学习了Runtime,对类和对象的结构,和一些消息转发有一些自己的理解,现在希望简单的应用下,就决定自己写一个简单的JSON与Model的相互转化,现在总结下。

 观察下面这个JSON数据和Model数据

  1. NSString *girlFriend = @"白菜";  
  2. id parmenters = @{  
  3.         @"girlFriend":girlFriend,  
  4.         @"age":@22.1,  
  5.         @"name":@"Lastdays",  
  6.         @"time":@"2016-03-18 5:55:49 +0000"  
  7. }; 
  1. @interfaceModel: NSObject  
  2.    
  3. @property NSNumber *age;  
  4. @property NSString *name;  
  5. @property NSString *girlFriend;  
  6. @property NSData *time;  
  7.    
  8. @end 

开始的时候仔细想了一下,如何能够动态的去添加属性值,并且根据对应的属性进行赋值,还要保证类型正确,这是我最开始考虑的问题。但是最核心问题就是 动态实现 。

我们一步一步来解决问题,首先我们先获取Model属性,取得Model的一些信息
获取Model属性

runtime提供了 class_copyPropertyList 来获取属性列表,OK,我们可以来看一下用它获取的数据是什么样的?查看runtime源码

  1. /***********************************************************************  
  2. * class_copyPropertyList. Returns a heap block containing the  
  3. * properties declared in the class, or nil if the class  
  4. * declares no properties. Caller must free the block.  
  5. * Does not copy any superclass's properties.  
  6. **********************************************************************/  
  7. objc_property_t*class_copyPropertyList(Class cls, unsigned int *outCount)  
  8. {  
  9.     old_property_list*plist;  
  10.     uintptr_titerator = 0;  
  11.     old_property**result = nil;  
  12.     unsigned int count = 0;  
  13.     unsigned int p, i;  
  14.    
  15.     if (!cls) {  
  16.         if (outCount) *outCount = 0;  
  17.         return nil;  
  18.     }  
  19.    
  20.     mutex_locker_tlock(classLock);  
  21.    
  22.     iterator = 0;  
  23.     while ((plist = nextPropertyList(cls, &iterator))) {  
  24.         count += plist->count;  
  25.     }  
  26.    
  27.     if (count > 0) {  
  28.         result = (old_property**)malloc((count+1) * sizeof(old_property*));  
  29.    
  30.         p = 0;  
  31.         iterator = 0;  
  32.         while ((plist = nextPropertyList(cls, &iterator))) {  
  33.             for (i = 0; i < plist->count; i++) {  
  34.                 result[p++] = property_list_nth(plist, i);  
  35.             }  
  36.         }  
  37.         result[p] = nil;  
  38.     }  
  39.    
  40.     if (outCount) *outCount = count;  
  41.     return (objc_property_t*)result;  
  1. typedef struct old_property*objc_property_t; 
  1. struct old_property {  
  2.     const char *name;  
  3.     const char *attributes;  
  4. }; 

从上面的三段runtime源码中,课本上就能判断出,其实返回结果就是一些old_property,并且每个old_property中含有对应的name和其他信息。

总结起来说就是**class_copyPropertyList**获取Model属性列表,属性列表里面的objc_property_t包含着这个属性的类型和名字等一些信息。

根据刚才的分析设计出以下结构:

  1. bash  
  2. -(id)modelToJsonObject:(NSObject *)model{  
  3.    
  4.     Class cls = self.class;  
  5.     unsigned int countProperty = 0;  
  6.     objc_property_t*propertys = class_copyPropertyList(cls,&countProperty);  
  7.     NSMutableDictionary *dic = [NSMutableDictionary new];  
  8.    
  9.     for (unsigned int i = 0; i<countProperty; i++) {  
  10.         PropertyInfo *propertyInfo = [[PropertyInfo alloc]initWithProperty:propertys[i]];  
  11.         if (propertyInfo.propertyName!=nil) {  
  12.             dic[propertyInfo.propertyName] = [selfLYModelSetJsonObjectWith:modelpropertyInfo:propertyInfo];  
  13.         }  
  14.     }  
  15.     return dic;  

PropertyInfo也就是属性信息,我们将Model的所有属性存放到 NSMutableDictionary 中,key就是属性名,Value就是PropertyInfo。

接下来开始获取Model的属性信息 PropertyInfo

我们可以通过property_getName来获取属性名

  1. const char *property_getName(objc_property_tprop)  
  2. {  
  3.     return oldproperty(prop)->name;  

接下来就是获取属性的类型和一些其他的信息。获取属性的信息其实和上面的原理差不多,我们使用property_copyAttributeList,

  1. objc_property_attribute_t*property_copyAttributeList(objc_property_tprop,   
  2.                                                       unsigned int *outCount)  
  3. {  
  4.     if (!prop) {  
  5.         if (outCount) *outCount = 0;  
  6.         return nil;  
  7.     }  
  8.    
  9.     mutex_locker_tlock(classLock);  
  10.     return copyPropertyAttributeList(oldproperty(prop)->attributes,outCount);  

看到这里,不往下继续分析源码了,其实可以看到,attributes就是我们想要的信息,其实每个property也是有自己对应的attributes。

这个attributes是什么样呢?翻看源码,找到了答案

  1. typedef struct {  
  2.     const char *name;        
  3.     const char *value;          
  4. } objc_property_attribute_t; 

加一下断点,看看

可以看到,name是T,Value是NSNumber,我们来获取下NSNumber这个属性类型。

  1. for (unsigned int i = 0; i<attrCount; i++) {  
  2.     if (attrs[i].name[0] == 'T') {  
  3.         size_tlen = strlen(attrs[i].value);  
  4.         if (len>3) {  
  5.             char name[len - 2];  
  6.             name[len - 3] = '';  
  7.             memcpy(name, attrs[i].value + 2, len - 3);  
  8.             _typeClass = objc_getClass(name);  
  9.         }  
  10.     }  

基本上我们想要的信息基本上都已经获取到了,现在接下来就是做动态设定。

中间做个插曲简单的说下Objc是动态语言,[receiver message]的执行过程当中,[receiver message]是会被动态编译的,Objc是动态语言,因此它会想尽办法将编译连接推迟到运行时来做。runtime这个时实运行系统就是来执行编译后的代码。

在这个消息发送过程中,objc_msgSend充当着很重要的角色,所以我们可以主动触发objc_msgSend,来模拟getter,setter方法获取属性值,或者建立。

我们通过SEL来定义选择器,选择器是什么?就是方法名的唯一标识符

根据刚才的想法,编写的代码***是这个样子

  1. -(instancetype)initWithProperty:(objc_property_t)property{  
  2.     _property = property;  
  3.    
  4.     const char *name = property_getName(property);  
  5.     if (name) {  
  6.         _propertyName = [NSStringstringWithUTF8String:name];  
  7.     }  
  8.     unsigned int attrCount;  
  9.     objc_property_attribute_t*attrs = property_copyAttributeList(property, &attrCount);  
  10.     for (unsigned int i = 0; i<attrCount; i++) {  
  11.         if (attrs[i].name[0] == 'T') {  
  12.             size_tlen = strlen(attrs[i].value);  
  13.             if (len>3) {  
  14.                 char name[len - 2];  
  15.                 name[len - 3] = '';  
  16.                 memcpy(name, attrs[i].value + 2, len - 3);  
  17.                 _typeClass = objc_getClass(name);  
  18.             }  
  19.         }  
  20.     }  
  21.     NSString *setter = [NSStringstringWithFormat:@"set%@%@:", [_propertyNamesubstringToIndex:1].uppercaseString, [_propertyNamesubstringFromIndex:1]];  
  22.     _setter =  NSSelectorFromString(setter);  
  23.     _getter = NSSelectorFromString(_propertyName);  
  24.    
  25.     return self;  

基本的准备工作,和一些问题都解决了,接下来可以写功能了。
JSON转Model

根据刚才说的,我们可以主动触发objc_msgSend,来模拟setter方法建立属性值。设计出以下方法

  1. -(void)LYModelSetPropertyWithModel:(id) modelvalue:(id)valuepropertyInfo:(PropertyInfo *) propertyInfo{  
  2.     ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, propertyInfo.setter, value);  

我们将Model的所有属性存放到 NSMutableDictionary 中,key就是属性名,Value就是PropertyInfo。

现在就可以动态设定了

  1. -(BOOL)LYModelSelectProperties:(NSDictionary *)dictonary{  
  2.    
  3.     ClassInfo *cls = [[ClassInfo alloc]initWithClass:object_getClass(self)];  
  4.     id key, value;  
  5.     NSArray *keys = [dictonaryallKeys];  
  6.     NSUInteger count = [keyscount];  
  7.     for (int i = 0; i < count; i++){  
  8.         key = [keysobjectAtIndex: i];  
  9.         value = [dictonaryobjectForKey: key];  
  10.    
  11.         if (cls.propertyInfo[key]) {  
  12.             [selfLYModelSetPropertyWithModel:selfvalue:valuepropertyInfo:cls.propertyInfo[key]];  
  13.         }  
  14.     }  
  15.     return YES;  

完成动态设定
Model转JSON

原理跟JSON转Model

我们可以主动触发objc_msgSend,来模拟getter方法来获取属性值。

  1. -(id)LYModelSetJsonObjectWith:(id)modelpropertyInfo:(PropertyInfo *)propertyInfo{  
  2.     id value = ((id (*)(id, SEL))(void *) objc_msgSend)((id)model, propertyInfo.getter);  
  3.     return value;  

建立NSDictionary

  1. -(id)modelToJsonObject:(NSObject *)model{  
  2.    
  3.     Class cls = self.class;  
  4.     unsigned int countProperty = 0;  
  5.     objc_property_t*propertys = class_copyPropertyList(cls,&countProperty);  
  6.     NSMutableDictionary *dic = [NSMutableDictionary new];  
  7.    
  8.     for (unsigned int i = 0; i<countProperty; i++) {  
  9.         PropertyInfo *propertyInfo = [[PropertyInfo alloc]initWithProperty:propertys[i]];  
  10.         if (propertyInfo.propertyName!=nil) {  
  11.             dic[propertyInfo.propertyName] = [selfLYModelSetJsonWith:modelpropertyInfo:propertyInfo];  
  12.         }  
  13.     }  
  14.     return dic;  

完成获取
测试

  1. NSString *girlFriend = @"白菜";  
  2.     id parmenters = @{  
  3.                       @"girlFriend":girlFriend,  
  4.                       @"age":@22.1,  
  5.                       @"name":@"Lastdays",  
  6.                       @"time":@"2016-03-18 5:55:49 +0000"  
  7.                       };  
  8.    
  9.     Model *model = [ModelLYModelWithJSON:parmenters];  
  10.     NSLog(@"%@",model.girlFriend);  
  11.     NSLog(@"%@",model.name);  
  12.     NSLog(@"%@",model.age);  
  13.     NSLog(@"%@",model.time);  
  14.    
  15.     NSLog(@"========================================");  
  16.    
  17.     NSDictionary *jsonObject= [modelLYModelToJson];  
  18.     NSLog(@"%@",jsonObject); 

结果:

总结

简单的JSON Model转换库,关键点就是在于对runtime的理解。就当自己的一个小练习,后续会继续维护,让它对更多类型进行支持。代码结构上可能不是那么好,后续会将整体的结构重新设计下,增加可读性,也欢迎来提出建议。

责任编辑:陈琳 来源: 伯乐在线
相关推荐

2016-11-29 10:20:50

SwiftJSONModel工具库

2015-10-28 09:55:39

Swift解析生产库

2011-04-22 13:44:34

JacksonJSON

2014-07-17 10:06:02

Model-View-iOS App

2010-06-30 11:16:50

SQL Server

2009-06-15 15:10:02

Java数据转换JSON

2015-08-07 09:33:24

RuntimeModel

2022-10-13 21:07:48

数据库SQL Server

2009-08-13 09:33:07

JavaBean到XM

2010-01-05 14:49:03

JSON格式

2015-11-24 09:53:22

AngularJSXMLJSON

2020-06-10 14:16:57

iOS 13.6 be苹果更新

2010-01-08 10:49:21

JSON 转换工具

2020-10-22 08:01:52

XMLJSON转换

2012-12-24 14:53:44

ios

2024-03-12 09:10:21

GoarenaAPI

2010-01-08 10:24:38

转换JSON

2021-08-20 16:37:42

SparkSpark Strea

2015-09-01 10:37:54

ios静态库开发

2021-01-04 05:40:58

MySQL数据库
点赞
收藏

51CTO技术栈公众号