Json解析到Model的技巧

情景再现:在项目中从服务器获取数据的时候,经常采用json格式的数据,为了能方便的使用这些数据,项目中会把json转化为model。

之前我们的项目中是这么用的:

FBC9E23D-E2BD-4E04-A5EE-869024193DAA.png

很复杂,很乱,对不对,然而这才只是二十多个字段中的5个,(:зゝ∠),一定有更好的方法。

如果我们能够在动态地去获取对象的属性名就好了,只要json的key和对象的属性名一样,那么就可以利用for循环以可kvc赋值了。在Java中,我们可以利用反射来做到这一点,同样的,在OC中,我们可以利用runtime的特性来实现。

代码如下:

    NSDictionary *dic = @{@"name" : @"小王",
                          @"no"   : @"123",
                          @"rank" : @1,
                          @"sex"  : @0};
    Student *student = [[Student alloc] init];
    u_int count;
    objc_property_t *properties  =class_copyPropertyList([Student class], &count);
    for (int i = 0;i<count;i++)
    {
        const char* propertyName =property_getName(properties[i]);
        NSString *property = [NSString stringWithUTF8String: propertyName];
        [student setValue:dic[property] forKey:property];
    }
    free(properties);

结果如下,DONE!:

923458B1-5A0F-4288-9782-A62ACE0D2B2E.png

优点:这种扩展性强,并且与dic存储的类型无关,例如将@"rank" : @1改成@"rank" : @"1"后,也能得到正确的输出。
缺点;但是要求属性名和接口返回json数据中的key一一对应。

扩展一
封装一下,让Model类继承基类就可以直接使用。创建一个JsonModel类,代码如下:

#import "JsonModel.h"
#import "objc/runtime.h"

@implementation JsonModel

- (id)initWithDic:(NSDictionary *)dic {
    self = [super init];
    if (self) {
        u_int count;
        objc_property_t *properties  =class_copyPropertyList([self class], &count);
        for (int i = 0;i<count;i++) {
            const char* propertyName =property_getName(properties[i]);
            NSString *property = [NSString stringWithUTF8String: propertyName];
            [self setValue:dic[property] forKey:property];
        }
        free(properties);
    }
    return self;
}

@end

使用时,让Student类继承JsonModel类,然后就可以方便的初始化Student类了。

Student *student = [[Student alloc] initWithDic:dic];

扩展二
如果由于各种原因,接口返回数据的key和model的属性名不能统一,那么如何处理呢?初步想法是构造一个映射关系,代码如下:

#import "JsonModel.h"
#import "objc/runtime.h"

@interface JsonModel()
@end

@implementation JsonModel

- (id)initWithDic:(NSDictionary *)dic {
    self = [super init];
    if (self) {
        u_int count;
        objc_property_t *properties  =class_copyPropertyList([self class], &count);
        for (int i = 0;i<count;i++){
            const char* propertyName =property_getName(properties[i]);
            NSString *property = [NSString stringWithUTF8String: propertyName];
            if (dic[property] != nil) {
                [self setValue:dic[property] forKey:property];
            } else {
                NSDictionary * correlation = [[self class] getKeyAndPropertyCorrelation];
                if (correlation != nil) {
                    [self setValue:dic[correlation[property]] forKey:property];
                }
            }
        }
        free(properties);
    }
    return self;
}

+ (NSDictionary *)getKeyAndPropertyCorrelation {
    return nil;
}

@end
#import "Student.h"

@implementation Student

+ (NSDictionary *)getKeyAndPropertyCorrelation {
    return @{@"name" : @"firstname",
             @"no"   : @"number"};
}

@end

使用方法:通过重写静态方法getKeyAndPropertyCorrelation去设置关系映射表。

扩展三
github上有一个开源Json解析第三方库JsonModel,包含了很多强大的功能。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容