軟件開發過程中,需要解析各種各樣的數據.如最基礎的plist文件,從網絡下載獲取的json數據,以及xml網頁數據,還有比較重要的Core Data數據.
下面我來分享一種快速將json文件中的字典轉為模型的方法.雖然很多人在用第三方類庫解析json數據,不過將json文件中的字典轉為模型內部的實現原理還是需要了解一下的.
下面是BaseModel.h聲明文件,向外界開方了兩個方法:
第7行的方法是實現json文件中的字典轉模型;
第10行方法是防止出現特殊類型的數據無法轉為模型而導致程序異常.
1 BaseModel.h 2 3 #import <Foundation/Foundation.h> 4 5 @interface BaseModel : NSObject 6 7 - (instancetype)initWithDictionary:(NSDictionary *)jsonDictionary; 8 9 // 將json中的value值交給model的屬性(覆寫該方法可以將json文件中特殊的數據加到model中)特殊類型如:NSNull類型數據10 - (void)setAttributesWithDictionary:(NSDictionary *)jsonDict;11 12 @end
下面是BaseModel.m實現文件
1 BaseModel.m 2 3 #import "BaseModel.h" 4 5 @implementation BaseModel 6 7 - (instancetype)initWithDictionary:(NSDictionary *)jsonDictionary 8 { 9 self = [super init];10 11 if (self) {12 // 將jsonDictionary字典的value值交給model的屬性值13 [self setAttributesWithDictionary:jsonDictionary];14 }15 return self;16 }17 18 // 將jsonDictionary字典的value值交給model的屬性值19 - (void)setAttributesWithDictionary:(NSDictionary *)jsonDictionary20 {21 // 獲取映射關系22 NSDictionary *modelDictionary = [self attributesModel:jsonDictionary];23 24 for (NSString *jsonKey in modelDictionary) {25 // 取得屬性名26 NSString *modelAttributesNmae = [modelDictionary objectForKey:jsonKey];27 28 // 取得Value值29 id jsonValue = [jsonDictionary objectForKey:jsonKey];30 31 // 獲取屬性的setter方法32 SEL setterSEL = [self stringToSEL:modelAttributesNmae];33 34 // 如果Value值為NULL,則賦值為""(什么也沒有)35 if ([jsonValue isKindOfClass:[NSNull class]]) {36 jsonValue = @"";37 }38 39 // Warning:PerformSelector may cause a leak because its selector is unknown(PerformSelector可能導致內存泄漏,因為它選擇器是未知的)40 if ([self respondsToSelector:setterSEL]) {41 [self performSelector:setterSEL withObject:jsonValue];42 }43 44 }45 }46 47 // 將字典中的key和model的屬性名映射48 - (NSDictionary *)attributesModel:(NSDictionary *)jsonDictionary49 {50 NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];51 52 // 屬性名和jsonDictionary的key一樣53 for (NSString *jsonKey in jsonDictionary) {54 [dict setValue:jsonKey forKey:jsonKey];55 }56 return dict;57 }58 59 // 獲取屬性的setter方法60 - (SEL)stringToSEL:(NSString *)modelAttributes61 {62 // 截取屬性名的首字母63 NSString *firstString = [modelAttributes substringToIndex:1];64 65 // 首字母大寫66 firstString = [firstString uppercaseString];67 68 // 截取除首字母以外的其它屬性名內容69 NSString *endString = [modelAttributes substringFromIndex:1];70 71 // 拼接setter方法名72 NSString *selString = [NSString stringWithFormat:@"set%@%@:",firstString, endString];73 74 // 將字符串轉化為方法75 SEL selector = NSSelectorFromString(selString);76 77 return selector;78 }79 80 @end
其中BaseModel.m實現文件的第41行會報一個警告,警告的內容上面已經給出了.
到此為止,一個將json文件中的字典轉為模型的類已經實現了.
BaseModel的使用大家可以自己測試一下,在這里就不在演示了.
新聞熱點
疑難解答