MJExtension 是一套「字典與模型互相轉換」的輕量級框架,能完成四件事:字典轉模型、模型轉字典、字典陣列轉模型陣列、模型陣列轉字典陣列。
GitHub 專案:https://github.com/CoderMJLee/MJExtension
主要用法集中在 NSObject+MJKeyValue.h 這個分類中,以下用實例逐一示範。
@interface MJUser : NSObject
@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) NSString *icon;
@property (assign, nonatomic) unsigned int age;
@property (strong, nonatomic) NSNumber *height;
@property (strong, nonatomic) NSDecimalNumber *money;
@property (assign, nonatomic) Sex sex;
@property (assign, nonatomic, getter=isGay) BOOL gay;
@end
// 字典 -> 模型
NSDictionary *dict = @{
@"name" : @"Jack",
@"icon" : @"lufy.png",
@"age" : @"20",
@"height" : @1.55,
@"money" : @"100.9",
@"sex" : @(SexFemale),
@"gay" : @"1"
};
MJUser *user = [MJUser mj_objectWithKeyValues:dict];
值得注意的一點是:即使字典裡的 age 是字串 "20",MJExtension 也會自動轉型成 unsigned int,不必手動處理。
NSString *jsonString = @"{\"name\":\"Jack\", \"icon\":\"lufy.png\", \"age\":20, \"height\":333333.7}";
MJUser *user = [MJUser mj_objectWithKeyValues:jsonString];
@interface MJStatus : NSObject
@property (copy, nonatomic) NSString *text;
@property (strong, nonatomic) MJUser *user;
@property (strong, nonatomic) MJStatus *retweetedStatus;
@end
NSDictionary *dict = @{
@"text" : @"是啊,今天天氣確實不錯!",
@"user" : @{ @"name" : @"Jack", @"icon" : @"lufy.png" },
@"retweetedStatus" : @{
@"text" : @"今天天氣真不錯!",
@"user" : @{ @"name" : @"Rose", @"icon" : @"nami.png" }
}
};
MJStatus *status = [MJStatus mj_objectWithKeyValues:dict];
// 直接多層取值
NSString *icon2 = status.retweetedStatus.user.icon;
巢狀結構會被自動遞迴解析,連轉推內容裡的作者資訊都能一次搞定。
這種情況需要透過 mj_objectClassInArray 明確告訴框架每個陣列屬性對應的模型型別:
@implementation MJStatusResult
+ (NSDictionary *)mj_objectClassInArray {
return @{
@"statuses" : @"MJStatus",
@"ads" : @"MJAd"
};
}
@end
MJStatusResult *result = [MJStatusResult mj_objectWithKeyValues:dict];
for (MJStatus *status in result.statuses) {
NSLog(@"%@ %@", status.text, status.user.name);
}
for (MJAd *ad in result.ads) {
NSLog(@"%@ %@", ad.image, ad.url);
}
後端欄位名與屬性名不一致時(例如 id 對 ID、desciption 對 desc),用 mj_replacedKeyFromPropertyName 處理,且支援形如 name.oldName、name.info[1].nameChangedTime 的多級路徑:
NSDictionary *dict = @{
@"id" : @"20",
@"desciption" : @"好孩子",
@"name" : @{
@"newName" : @"lufy",
@"oldName" : @"kitty",
@"info" : @[ @"test-data", @{@"nameChangedTime" : @"2013-08-07"} ]
},
@"other" : @{ @"bag" : @{ @"name" : @"小書包", @"price" : @100.7 } }
};
MJStudent *stu = [MJStudent mj_objectWithKeyValues:dict];
NSArray *dictArray = @[
@{ @"name" : @"Jack", @"icon" : @"lufy.png" },
@{ @"name" : @"Rose", @"icon" : @"nami.png" }
];
NSArray *userArray = [MJUser mj_objectArrayWithKeyValuesArray:dictArray];
for (MJUser *user in userArray) {
NSLog(@"%@ %@", user.name, user.icon);
}
MJUser *user = [[MJUser alloc] init]; user.name = @"Jack"; user.icon = @"lufy.png"; MJStatus *status = [[MJStatus alloc] init]; status.user = user; status.text = @"今天的心情不錯!"; NSDictionary *statusDict = status.mj_keyValues; // 只取指定欄位 NSDictionary *partial = [status mj_keyValuesWithKeys:@[@"text"]]; // 排除指定欄位 NSDictionary *ignored = [stu mj_keyValuesWithIgnoredKeys:@[@"bag", @"oldName", @"nowName"]]; // 直接輸出 JSON 字串 NSString *json = stu.mj_JSONString;
補充一個實務上很關鍵的細節:預設情況下,模型轉字典時 key 會參考 replacedKeyFromPropertyName 的映射結果。若你希望輸出還原成原始屬性名,可以關閉這個行為:
[MJStudent mj_referenceReplacedKeyWhenCreatingKeyValues:NO];
NSArray *userArray = @[user1, user2]; NSArray *dictArray = [MJUser mj_keyValuesArrayWithObjectArray:userArray];
NSManagedObjectContext *context = nil; MJUser *user = [MJUser mj_objectWithKeyValues:dict context:context]; [context save:nil];
只要加上一個宏,MJExtension 就會自動為類別實作歸檔與解檔所需的全部方法:
@implementation MJBag
// 一行搞定 NSCoding
MJExtensionCodingImplementation
// 若要排除特定屬性:
// + (NSArray *)mj_ignoredCodingPropertyNames { return @[@"name"]; }
@end
// 使用
[NSKeyedArchiver archiveRootObject:bag toFile:file];
MJBag *decodedBag = [NSKeyedUnarchiver unarchiveObjectWithFile:file];
後端習慣用 snake_case、前端習慣 camelCase 時,用這個方法一次對應:
+ (NSDictionary *)mj_replacedKeyFromPropertyName {
return @{
@"nickName" : @"nick_name",
@"salePrice" : @"sale_price",
@"runSpeed" : @"run_speed"
};
}
MJDog *dog = [MJDog mj_objectWithKeyValues:dict];
實務上常見的需求是把字串日期轉成 NSDate,或把 null 轉為空字串,這時可實作 mj_newValueFromOldValue 進行值層級的轉換:
MJBook *book = [MJBook mj_objectWithKeyValues:dict]; NSLog(@"%@ %@", book.name, book.publishedTime);
整體來說,MJExtension 把「字典轉模型」這類樣板程式碼壓縮到一行,特別適合應對後端欄位命名不一致、多層巢狀 JSON 與陣列模型化的場景。