iOS中使用KVC实现JSON数据与Objective-C实体对象之间的转换

来源:互联网 发布:小葫芦数据检测作假 编辑:程序博客网 时间:2024/04/26 19:31
JSON数据,一种极其常用的数据传输格式,在iOS开发当中,经常会遇到需要将JSON格式数据转换为定义的实体,如将一大串联络人的json数据转换为Contact对象的数组等,想必大家都知道有一种最常见的方式,如下:
  1. 首先将JSON解析成字典(NSDictionary)或数组(NSArray);
  2. 然后使用objectForKey分别对Contact对象的属性进行赋值。
以上方式,存在的问题:
1、大量的objectForKey,导致代码量大,增加维护成本;
2、如果JSON中增加一个字段,对应在实体对象当中,增加一个属性,同时还需要在json解析的地方进行赋值。
如果在开发中使用KVC,来实现JSON数据与实体对象之间的转换,能够很好的解决以上方式存在的问题,不说了,直接贴代码,有兴趣的可以在日常的开发当中尝试一下。
- (void)serialization:(NSString*)json{    NSDictionary *dataSource = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding]                                                               options:NSJSONReadingMutableLeaves                                                                 error:nil];    [self convert:dataSource];}- (void)serializationWithDictionary:(NSMutableDictionary*)dictionary{    [self convert:dictionary];}- (void)convert:(NSDictionary*)dataSource{    for (NSString *key in [dataSource allKeys]) {        if ([[self propertyKeys] containsObject:key]) {            id propertyValue = [dataSource valueForKey:key];            if (![propertyValue isKindOfClass:[NSNull class]]                && propertyValue != nil) {                [self setValue:propertyValue                        forKey:key];            }        }    }}- (NSArray*)propertyKeys{    unsigned int outCount, i;    objc_property_t *properties = class_copyPropertyList([self class], &outCount);    NSMutableArray *propertys = [NSMutableArray arrayWithCapacity:outCount];    for (i = 0; i<outCount; i++)    {        objc_property_t property = properties[i];        const char* char_f =property_getName(property);        NSString *propertyName = [NSString stringWithUTF8String:char_f];        [propertys addObject:propertyName];    }    free(properties);    return propertys;}

以上是核心代码,当然你需要引入

<objc/runtime.h>

然后创建一个NSObject的Category,将以上代码加入就OK了,超级简单。

0 0
原创粉丝点击