首页 > 学院 > 开发设计 > 正文

最简单的 json或字典 转 model

2019-11-09 18:17:56
字体:
来源:转载
供稿:网友

前言

我们在iOS开发中,一般会使用MVC或者MVVM等模式。当我们从接口中拿到数据时,我们需要把数据转成模型使用。下面我就带大家一起用runtime一步一步的来完成这个转换框架.(比较简单的model不用runtime也可以的) .

1、先写一个简单的字典到模型的转换

模型TestModel
@interface TestModel : NSObject@PRoperty (nonatomic, copy) NSString *name;@property (nonatomic, copy) NSString *phone;@property (nonatomic, copy) NSString *address;@property (nonatomic, assign) NSInteger age;@end控制器ViewController中
@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    self.title = @"字典转模型";    NSDictionary *dicTest = @{@"name":@"张三",                              @"phone":@"110",                              @"age":@"10"};    TestModel *model = [TestModel yj_initWithDictionary:dicTest];    NSLog(@"model-----name:%@, phone:%@, address:%@, age:%@", model.name, model.phone, model.address, @(model.age));}@end字典转模型的分类中
@implementation NSObject (YJModelDicTransform)//字典转模型+ (instancetype)yj_initWithDictionary:(NSDictionary *)dic{    id myObj = [[self alloc] init];    unsigned int outCount;    //获取类中的所有成员属性    objc_property_t *arrPropertys = class_copyPropertyList([self class], &outCount);    for (NSInteger i = 0; i < outCount; i ++) {        objc_property_t property = arrPropertys[i];        //获取属性名字符串        //model中的属性名        NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)];        id propertyValue = dic[propertyName];        if (propertyValue != nil) {            [myObj setValue:propertyValue forKey:propertyName];        }    }    free(arrPropertys);    return myObj;}控制台打印

2016-12-19 15:55:18.231 YJModelDicTransform[1627:125724] model-----name:张三, phone:110, address:(null), age:10

这个地方我觉得这里是不需要用runtime啊, 比如这样写,同样可以完成需求,当然需要保证dic中key和 属性一一对应.       NSArray *keyArray = [dict allKeys];                    for (NSString *key in keyArray) {              [self setValue:dict[key] forKey:key] ;          }这个方法也要有,防止服务器出错时的崩溃- (void)setValue:(id)value forUndefinedKey:(NSString *)key  {        }到这步,我的需求基本就完了,但是还是向下看下,学习学习 .

2、模型中嵌套有模型

第一步完成后我们已经可以自动完成字典和模型的转换了,但是还不完善,比如我们的字典的value中如果有字典或者数组类型的话,程序就识别不了,所以我们现在就来处理这种情况

先通过runtime来获取模型中属性的类型,然后根据不同类型来处理

@interface TestModel : NSObject@property (nonatomic, copy) NSString *name;@property (nonatomic, copy) NSString *phone;@property (nonatomic, copy) NSString *address;@property (nonatomic, assign) NSInteger age;//模型中嵌套UserModel模型@property (nonatomic, strong) UserModel *user;@end@interface UserModel : NSObject@property (nonatomic, copy) NSString *userName;@property (nonatomic, copy) NSString *userId;@end
NSString *const YJClassType_object  =   @"对象类型";NSString *const YJClassType_basic   =   @"基础数据类型";NSString *const YJClassType_other   =   @"其它";
@implementation NSObject (YJModelDicTransform)+ (instancetype)yj_initWithDictionary:(NSDictionary *)dic{    id myObj = [[self alloc] init];    unsigned int outCount;    //获取类中的所有成员属性    objc_property_t *arrPropertys = class_copyPropertyList([self class], &outCount);    for (NSInteger i = 0; i < outCount; i ++) {        objc_property_t property = arrPropertys[i];        //获取属性名字符串        //model中的属性名        NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)];        id propertyValue = dic[propertyName];        if (propertyValue == nil) {            continue;        }        //获取属性是什么类型的        NSDictionary *dicPropertyType = [self propertyTypeFromProperty:property];        NSString *propertyClassType = [dicPropertyType objectForKey:@"classType"];        NSString *propertyType = [dicPropertyType objectForKey:@"type"];        if ([propertyType isEqualToString:YJClassType_object]) {            if ([propertyClassType isEqualToString:@"NSArray"] || [propertyClassType isEqualToString:@"NSMutableArray"]) {                //数组类型,现在还用不了,因为还没有方法知道数组中保存的是什么类型,后面会处理            }            else if ([propertyClassType isEqualToString:@"NSDictionary"] || [propertyClassType isEqualToString:@"NSMutableDictionary"]) {                //字典类型   不考虑,一般不会用字典,用自定义model            }            else if ([propertyClassType isEqualToString:@"NSString"]) {                //字符串类型                if (propertyValue != nil) {                    [myObj setValue:propertyValue forKey:propertyName];                }            }            else {                //自定义类型,循环调用,一直到不是自定义类型                propertyValue = [NSClassFromString(propertyClassType) yj_initWithDictionary:propertyValue];                if (propertyValue != nil) {                    [myObj setValue:propertyValue forKey:propertyName];                }            }        }        else if ([propertyType isEqualToString:YJClassType_basic]) {            //基本数据类型            if ([propertyClassType isEqualToString:@"c"]) {                //bool类型                NSString *lowerValue = [propertyValue lowercaseString];                if ([lowerValue isEqualToString:@"yes"] || [lowerValue isEqualToString:@"true"]) {                    propertyValue = @(YES);                } else if ([lowerValue isEqualToString:@"no"] || [lowerValue isEqualToString:@"false"]) {                    propertyValue = @(NO);                }            }            else {                propertyValue = [[[NSNumberFormatter alloc] init] numberFromString:propertyValue];            }            if (propertyValue != nil) {                [myObj setValue:propertyValue forKey:propertyName];            }        }        else {            //其他类型        }    }    free(arrPropertys);    return myObj;}//获取属性的类型- (NSDictionary *)propertyTypeFromProperty:(objc_property_t)property{    //获取属性的类型, 类似 T@"NSString",C,N,V_name    T@"UserModel",&,N,V_user    NSString *propertyAttrs = @(property_getAttributes(property));    NSMutableDictionary *dicPropertyType = [NSMutableDictionary dictionary];    //截取类型    NSRange commaRange = [propertyAttrs rangeOfString:@","];    NSString *propertyType = [propertyAttrs substringWithRange:NSMakeRange(1, commaRange.location - 1)];    NSLog(@"属性类型:%@, %@", propertyAttrs, propertyType);    if ([propertyType hasprefix:@"@"] && propertyType.length > 2) {        //对象类型        NSString *propertyClassType = [propertyType substringWithRange:NSMakeRange(2, propertyType.length - 3)];        [dicPropertyType setObject:propertyClassType forKey:@"classType"];        [dicPropertyType setObject:YJClassType_object forKey:@"type"];    }    else if ([propertyType isEqualToString:@"q"]) {        //NSInteger类型        [dicPropertyType setObject:@"NSInteger" forKey:@"classType"];        [dicPropertyType setObject:YJClassType_basic forKey:@"type"];    }    else if ([propertyType isEqualToString:@"d"]) {        //CGFloat类型        [dicPropertyType setObject:@"CGFloat" forKey:@"classType"];        [dicPropertyType setObject:YJClassType_basic forKey:@"type"];    }    else if ([propertyType isEqualToString:@"c"]) {        //BOOL类型        [dicPropertyType setObject:@"BOOL" forKey:@"classType"];        [dicPropertyType setObject:YJClassType_basic forKey:@"type"];    }    else {        [dicPropertyType setObject:YJClassType_other forKey:@"type"];    }    return dicPropertyType;}控制器中
- (void)viewDidLoad {    [super viewDidLoad];    self.title = @"字典转模型";    NSDictionary *dicTest = @{@"name":@"张三",                              @"phone":@"110",                              @"age":@"10",                              @"user":@{@"userId":@"2"}};    TestModel *model = [TestModel yj_initWithDictionary:dicTest];    NSLog(@"model-----name:%@, phone:%@, address:%@, age:%@, userId:%@, userName:%@", model.name, model.phone, model.address, @(model.age), model.user.userId, model.user.userName);}控制台打印

2016-12-19 16:39:52.079 YJModelDicTransform[1851:143085] 属性类型:T@"NSString",C,N,V_name, @"NSString"

2016-12-19 16:39:52.080 YJModelDicTransform[1851:143085] 属性类型:T@"NSString",C,N,V_phone, @"NSString"

2016-12-19 16:39:52.080 YJModelDicTransform[1851:143085] 属性类型:Tq,N,V_age, q

2016-12-19 16:39:52.081 YJModelDicTransform[1851:143085] 属性类型:T@"UserModel",&,N,V_user, @"UserModel"

2016-12-19 16:39:52.081 YJModelDicTransform[1851:143085] 属性类型:T@"NSString",C,N,V_userId, @"NSString"

2016-12-19 16:39:52.081 YJModelDicTransform[1851:143085] model-----name:张三, phone:110, address:(null), age:10, userId:2, userName:(null)

在类中的声明为 

T@“NSNumber” 标记了属于什么类型N            线程安全 相当与Objective-C中的nonmaticR            不可变,R相当与Objective-C中的readonly,C相当于copy        V_name        去掉V_,name就是变量名

通过对type进行处理就可以获得属性的类型。从而进行下一步处理。

注意点:class_copyPropertyList返回的仅仅是对象类的属性,class_copyIvarList返回类的所有属性和变量,在swift中如let a: Int? 是无法通过class_copyPropertyList返回的。

看完了,开个简化版吧,  我是让model都继承rootModel, 他采用了给NSObject加类别, 都可以,   加类别 好处是 现有的工程几乎不用动,坏处是,以后再扩展不太方便  ,   继承rootModel好处是 扩展容易 , 比较适合一个新的工程 .
+ (id)objectWithDictionary:(NSDictionary * )dic  {            id myObj = [[self alloc] init];        unsigned int outCount;        //获取类中的所有成员属性    objc_property_t *arrPropertys = class_copyPropertyList([self class], &outCount);        for (NSInteger i = 0; i < outCount; i ++) {        objc_property_t property = arrPropertys[i];                //获取属性名字符串        //model中的属性名        NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)];        id propertyValue = dic[propertyName];                if ([propertyValue isKindOfClass:[NSDictionary class] ]) {            NSString * valueType =[self getPropertyType: property ];            Class valueClass = NSClassFromString(valueType) ;            // 递归调用,多少层的model都可以,            id value = [valueClass objectWithDictionary:propertyValue];            [myObj setValue:value forKey:propertyName];            continue ;        }                if (propertyValue != nil) {            [myObj setValue:propertyValue forKey:propertyName];        }    }        free(arrPropertys);    //         -------------------方法二 : 不用runtime试试, 经过拼命挣扎, 结果表明,只能对简单模型有效,对模型嵌套无效,主要失败原因,不能动态的获得嵌套模型的类名,获得类名或许只能通过runtime了//        for (NSString * key in dic.allKeys) {//    //            [myObj setValue:dic[key] forKey:key ];//    //        }//        return myObj;}+ (NSString *) getPropertyType:(objc_property_t)property {        //获取属性的类型, 类似 T@"NSString",C,N,V_name    T@"UserModel",&,N,V_user    NSString *propertyAttrs = @(property_getAttributes(property));        //截取类型    NSRange commaRange = [propertyAttrs rangeOfString:@","];    NSString *propertyType = [propertyAttrs substringWithRange:NSMakeRange(3, commaRange.location - 4)];    NSLog(@"属性类型:%@, 截取后%@", propertyAttrs, propertyType);        return propertyType ;    }

3、处理模型中有数组属性的情况

第二步之后程序可以处理模型中包含模型的情况, 但是还不能处理模型中有数组的情况,因为数组中存储的类型需要人为的告诉程序,下面我们添加一个协议来来处理这种情况

先创建一个协议, 然后让分类遵循它

@protocol YJModelDicTransform <NSObject>@optional/** *  数组中存储的类型 * *  @return key --- 属性名,  value --- 数组中存储的类型 */+ (NSDictionary *)yj_objectClassInArray;@end@interface NSObject (YJModelDicTransform)<YJModelDicTransform>+ (instancetype)yj_initWithDictionary:(NSDictionary *)dic;@end在model中实现这个方法
@implementation TestModel+ (NSDictionary *)yj_objectClassInArray{    return @{@"arrUsers":@"UserModel"};}+ (NSDictionary *)yj_propertykeyReplacedWithValue{    return @{@"_id":@"id"};}@end
//字典转模型+ (instancetype)yj_initWithDictionary:(NSDictionary *)dic{    id myObj = [[self alloc] init];    unsigned int outCount;    //获取类中的所有成员属性    objc_property_t *arrPropertys = class_copyPropertyList([self class], &outCount);    for (NSInteger i = 0; i < outCount; i ++) {        objc_property_t property = arrPropertys[i];        //获取属性名字符串        //model中的属性名        NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)];        id propertyValue = dic[propertyName];        if (propertyValue == nil) {            continue;        }        //获取属性是什么类型的        NSDictionary *dicPropertyType = [self propertyTypeFromProperty:property];        NSString *propertyClassType = [dicPropertyType objectForKey:@"classType"];        NSString *propertyType = [dicPropertyType objectForKey:@"type"];        if ([propertyType isEqualToString:YJClassType_object]) {            if ([propertyClassType isEqualToString:@"NSArray"] || [propertyClassType isEqualToString:@"NSMutableArray"]) {                //数组类型                if ([self respondsToSelector:@selector(yj_objectClassInArray)]) {                    id propertyValueType = [[self yj_objectClassInArray] objectForKey:propertyName];                    if ([propertyValueType isKindOfClass:[NSString class]]) {                        propertyValue = [NSClassFromString(propertyValueType) yj_initWithArray:propertyValue];                    }                    else {                        propertyValue = [propertyValueType yj_initWithArray:propertyValue];                    }                    if (propertyValue != nil) {                        [myObj setValue:propertyValue forKey:propertyName];                    }                }            }            else if ([propertyClassType isEqualToString:@"NSDictionary"] || [propertyClassType isEqualToString:@"NSMutableDictionary"]) {                //字典类型   不考虑,一般不会用字典,用自定义model            }            else if ([propertyClassType isEqualToString:@"NSString"]) {                //字符串类型                if (propertyValue != nil) {                    [myObj setValue:propertyValue forKey:propertyName];                }            }            else {                //自定义类型,循环调用,一直到不是自定义类型                propertyValue = [NSClassFromString(propertyClassType) yj_initWithDictionary:propertyValue];                if (propertyValue != nil) {                    [myObj setValue:propertyValue forKey:propertyName];                }            }        }        else if ([propertyType isEqualToString:YJClassType_basic]) {            //基本数据类型            if ([propertyClassType isEqualToString:@"c"]) {                //bool类型                NSString *lowerValue = [propertyValue lowercaseString];                if ([lowerValue isEqualToString:@"yes"] || [lowerValue isEqualToString:@"true"]) {                    propertyValue = @(YES);                } else if ([lowerValue isEqualToString:@"no"] || [lowerValue isEqualToString:@"false"]) {                    propertyValue = @(NO);                }            }            else {                propertyValue = [[[NSNumberFormatter alloc] init] numberFromString:propertyValue];            }            if (propertyValue != nil) {                [myObj setValue:propertyValue forKey:propertyName];            }        }        else {            //其他类型        }    }    free(arrPropertys);    return myObj;}

4、字典中包含一些iOS不能用的字段

有时候接口返回的数据中有id等iOS中和关键字重合的字段, 这个时候我们需要将id手动映射到模型中对应的属性中我们在刚刚创建的协议中在添加一个方法来处理
@protocol YJModelDicTransform <NSObject>@optional/** *  数组中存储的类型 * *  @return key --- 属性名,  value --- 数组中存储的类型 */+ (NSDictionary *)yj_objectClassInArray;/** *  替换一些字段 * *  @return key -- 模型中的字段, value --- 字典中的字段 */+ (NSDictionary *)yj_propertykeyReplacedWithValue;@end在model中实现这个方法
+ (NSDictionary *)yj_propertykeyReplacedWithValue{    return @{@"_id":@"id"};}
+ (instancetype)yj_initWithDictionary:(NSDictionary *)dic{    id myObj = [[self alloc] init];    unsigned int outCount;    //获取类中的所有成员属性    objc_property_t *arrPropertys = class_copyPropertyList([self class], &outCount);    for (NSInteger i = 0; i < outCount; i ++) {        objc_property_t property = arrPropertys[i];        //获取属性名字符串        //model中的属性名        NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)];        //字典中的属性名        NSString *newPropertyName;        if ([self respondsToSelector:@selector(yj_propertykeyReplacedWithValue)]) {            newPropertyName = [[self yj_propertykeyReplacedWithValue] objectForKey:propertyName];        }        if (!newPropertyName) {            newPropertyName = propertyName;        }        NSLog(@"属性名:%@", propertyName);        id propertyValue = dic[newPropertyName];        if (propertyValue == nil) {            continue;        }        //获取属性是什么类型的        NSDictionary *dicPropertyType = [self propertyTypeFromProperty:property];        NSString *propertyClassType = [dicPropertyType objectForKey:@"classType"];        NSString *propertyType = [dicPropertyType objectForKey:@"type"];        if ([propertyType isEqualToString:YJClassType_object]) {            if ([propertyClassType isEqualToString:@"NSArray"] || [propertyClassType isEqualToString:@"NSMutableArray"]) {                //数组类型                if ([self respondsToSelector:@selector(yj_objectClassInArray)]) {                    id propertyValueType = [[self yj_objectClassInArray] objectForKey:propertyName];                    if ([propertyValueType isKindOfClass:[NSString class]]) {                        propertyValue = [NSClassFromString(propertyValueType) yj_initWithArray:propertyValue];                    }                    else {                        propertyValue = [propertyValueType yj_initWithArray:propertyValue];                    }                    if (propertyValue != nil) {                        [myObj setValue:propertyValue forKey:propertyName];                    }                }            }            else if ([propertyClassType isEqualToString:@"NSDictionary"] || [propertyClassType isEqualToString:@"NSMutableDictionary"]) {                //字典类型   不考虑,一般不会用字典,用自定义model            }            else if ([propertyClassType isEqualToString:@"NSString"]) {                //字符串类型                if (propertyValue != nil) {                    [myObj setValue:propertyValue forKey:propertyName];                }            }            else {                //自定义类型                propertyValue = [NSClassFromString(propertyClassType) yj_initWithDictionary:propertyValue];                if (propertyValue != nil) {                    [myObj setValue:propertyValue forKey:propertyName];                }            }        }        else if ([propertyType isEqualToString:YJClassType_basic]) {            //基本数据类型            if ([propertyClassType isEqualToString:@"c"]) {                //bool类型                NSString *lowerValue = [propertyValue lowercaseString];                if ([lowerValue isEqualToString:@"yes"] || [lowerValue isEqualToString:@"true"]) {                    propertyValue = @(YES);                } else if ([lowerValue isEqualToString:@"no"] || [lowerValue isEqualToString:@"false"]) {                    propertyValue = @(NO);                }            }            else {                propertyValue = [[[NSNumberFormatter alloc] init] numberFromString:propertyValue];            }            if (propertyValue != nil) {                [myObj setValue:propertyValue forKey:propertyName];            }        }        else {            //其他类型        }    }    free(arrPropertys);    return myObj;}控制器中
- (void)viewDidLoad {    [super viewDidLoad];    self.title = @"字典转模型";    NSDictionary *dicTest = @{@"id":@"121",                              @"name":@"张三",                              @"phone":@"110",                              @"age":@"10",                              @"user":@{@"userId":@"2"},                              @"arrUsers":@[@{@"userId":@"2"},@{@"userId":@"2"},@{@"userId":@"2"}]};    TestModel *model = [TestModel yj_initWithDictionary:dicTest];    NSLog(@"model-----id:%@, name:%@, phone:%@, address:%@, age:%@, userId:%@, userName:%@", model._id, model.name, model.phone, model.address, @(model.age), model.user.userId, model.user.userName);    [model.arrUsers enumerateObjectsUsingBlock:^(UserModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {        NSLog(@"arrUser----userId:%@", obj.userId);    }];}控制台打印

2016-12-19 17:17:03.245 YJModelDicTransform[2099:158162] model-----id:121, name:张三, phone:110, address:(null), age:10, userId:2, userName:(null)

2016-12-19 17:17:03.245 YJModelDicTransform[2099:158162] arrUser----userId:2

2016-12-19 17:17:03.245 YJModelDicTransform[2099:158162] arrUser----userId:2

2016-12-19 17:17:03.245 YJModelDicTransform[2099:158162] arrUser----userId:2

到此,基本完成了字典转模型的功能。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表