情景再現:在項目中從服務器獲取數據的時候,經常采用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,包含了很多強大的功能。