背景:
JsonKit 接收網絡數據轉化成NSDictionary還算好用;
之前的項目 實體類 屬性字段比較少,偷懶的做法 是 遍歷 dictionary 利用objectForKey 逐個對 實體對象屬性賦值;
但是現在的項目開始變態了,實體非常多,而且 實體屬性字段 動輒幾十個,就像下面這種類型:
@interface PremiumCalculateResultDto : NSObject
@property (nonatomic, retain) NSMutableArray * premiumCalculateFeeList;
@property (nonatomic, retain) NSMutableArray * premiumCalculateCarShipTaxFeeList;
@property (nonatomic, retain) NSMutableArray * guCIVehiclePriceResultDtoList;
@property (nonatomic, retain) NSMutableArray * guCIInsureRiskItemResultDtoList;
@property (nonatomic, retain) NSMutableArray * guCIInsureDemandResultDtoList;
@interface PremiumCalculateFee : NSObject
@property (nonatomic, assign) double sumInsured;
@property (nonatomic, assign) double grossPremium;
@property (nonatomic, retain) NSString * riskCode;
@property (nonatomic, retain) NSMutableArray * premiumCalculateItemKindFeeList;
@property (nonatomic, assign) double benchmarkPremium;
@property (nonatomic, assign) double discount;
@interface PremiumCalculateItemKindFee : NSObject
@property (nonatomic, assign) double adjustRate;
@property (nonatomic, assign) double rate;
@property (nonatomic, assign) double netPremium;
@property (nonatomic, assign) double grossPremium;
@property (nonatomic, retain) NSString * riskCode;
@property (nonatomic, assign) double deductible;
@property (nonatomic, assign) double shortRate;
@property (nonatomic, retain) NSString * kindName;
@property (nonatomic, assign) double basePremium;
@property (nonatomic, assign) double benchmarkPremium;
@property (nonatomic, retain) NSString * kindCode;
@property (nonatomic, assign) double discount;
作爲一個正常人, 如何能忍受挨個遍歷手動forkey....
如果曾經你也是一名java程序員,或者看過java代碼, 你不難懷念 objectParser;傳入json數據和對應class,直接給你返回要用的對象;
既然沒有,那隻能自己幹!!!
首先要考慮的幾個問題:
1.實體屬性 類型的問題,特別是基本類型:double ,int, float等。
2.java中有泛型,而iOS卻沒有, 有什麼辦法將array中得對象class告知程序;
對於問題1.已經可以使用iOS特性KVC setObject forKey ,傳入 string , 它(編譯器)會自動轉化成需要的類型, 要注意的是 long 一定得聲明爲long long;
對於問題2.需要後臺嚴格遵守我們的約定:
傳入的array類型的數據爲key時候 ,命名統一爲xxxxList如:
guCIInsureDemandResultDtoList = (
{
我在截取類名時候 拼接類名 GuCIInsureDemandResultDto 然後反射爲對象,判斷dto實體是否有對應key的屬性, 然後利用KVC對屬性賦值;
此外:此外, 有些小工具是必不可少的;將Dto實體對象 轉化爲JSONString 然後post給服務器。算是一個與上述功能互逆的過程;之前很傻,在每個Dto裏面都寫了一個toDictionary方法;然後針對 屬性是否爲array類型做了迭代調用,將最終的Dto轉化爲 NSDictionary,然後利用JSONkit轉化爲JSONString傳給服務器;
爲此,由於忍受不了每個對象這麼寫;大量重複工作,費時費事,我還專門寫了小工具一枚,將java dto實體轉化爲 iosDto實體的工具;
現在想來: 直接擴展NSObject, 在裏面統一處理toDictionary方法,在toDictionary裏面 通過訪問jbj-c/runtime獲取類屬性和屬性列表;簡單的語句就可以搞定!
至此 : iOS 實體轉JSONString 和 JSONString 轉實體全部搞定!