先前介紹過 iOS 常用的網路框架 AFNetworking,其中 POST 請求的典型寫法如下:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
[manager POST:@"https://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
可以發現,請求成功後框架已經幫我們把 JSON 解析成一個字典 responseObject,接下來真正費工的是「如何處理這份資料」。實務上最常見的做法是透過 KVC 把字典轉成模型,而這件事有兩條路:自己刻程式碼,或使用第三方框架 MJExtension。
假設回傳的字典如下:
NSDictionary *dict = @{ @"name" : @"Jack", @"icon" : @"lufy.png", @"age" : @20 };
建立對應的模型:
@interface User : NSObject
@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) NSString *icon;
@property (assign, nonatomic) int age;
+(instancetype)accountWithDict:(NSDictionary *)dic;
@end
@implementation User
// 一行 KVC 搞定賦值,省下大量 setter 程式碼
+(instancetype)accountWithDict:(NSDictionary *)dic {
User *user = [[self alloc] init];
[user setValuesForKeysWithDictionary:dic];
return user;
}
@end
這種寫法在欄位少、結構扁平時綽綽有餘,但一旦遇到型別不一致或巢狀結構就會立刻破功。
MJExtension 是一個轉換速度快、使用簡單且非侵入式的 JSON 與模型互轉框架。使用前先把 MJExtension 資料夾中的所有原始碼拖進專案,再導入主標頭:
#import "MJExtension.h"
typedef enum { SexMale, SexFemale } Sex;
@interface User : NSObject
@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) NSString *icon;
@property (assign, nonatomic) unsigned int age;
@property (copy, nonatomic) NSString *height;
@property (strong, nonatomic) NSNumber *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" : @"true"
};
User *user = [User mj_objectWithKeyValues:dict];
// name=Jack, icon=lufy.png, age=20, height=1.550000, money=100.9, sex=1
@interface Status : NSObject
@property (copy, nonatomic) NSString *text;
@property (strong, nonatomic) User *user;
@property (strong, nonatomic) Status *retweetedStatus;
@end
NSDictionary *dict = @{
@"text" : @"Agree! Nice weather!",
@"user" : @{ @"name" : @"Jack", @"icon" : @"lufy.png" },
@"retweetedStatus" : @{
@"text" : @"Nice weather!",
@"user" : @{ @"name" : @"Rose", @"icon" : @"nami.png" }
}
};
Status *status = [Status mj_objectWithKeyValues:dict];
// text=Agree! Nice weather!, name=Jack, icon=lufy.png
// text2=Nice weather!, name2=Rose, icon2=nami.png
這種情況要先告訴 MJExtension 陣列裡裝的是哪個類別:
[StatusResult mj_setupObjectClassInArray:^NSDictionary *{
return @{
@"statuses" : @"Status",
@"ads" : @"Ad"
};
}];
// 等同於在 StatusResult.m 中實作 +mj_objectClassInArray
StatusResult *result = [StatusResult mj_objectWithKeyValues:dict];
for (Status *status in result.statuses) {
NSLog(@"%@ %@", status.text, status.user.name);
}
for (Ad *ad in result.ads) {
NSLog(@"%@ %@", ad.image, ad.url);
}
[Student mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
return @{
@"ID" : @"id",
@"desc" : @"desciption",
@"oldName" : @"name.oldName",
@"nowName" : @"name.newName",
@"nameChangedTime" : @"name.info[1].nameChangedTime",
@"bag" : @"other.bag"
};
}];
// 等同於在 Student.m 中實作 +mj_replacedKeyFromPropertyName
Student *stu = [Student mj_objectWithKeyValues:dict];
// ID=20, desc=kids, oldName=kitty, nowName=lufy, nameChangedTime=2013-08
// bagName=a red bag, bagPrice=100.700000
這裡的 name.info[1].nameChangedTime 特別實用——它能直接鑽進陣列的第二個元素取值,省去大量手動解析。
NSArray *userArray = [User mj_objectArrayWithKeyValuesArray:dictArray];
for (User *user in userArray) {
NSLog(@"%@ %@", user.name, user.icon);
}
NSDictionary *statusDict = status.mj_keyValues;
/*
{
text = "Nice mood!";
user = { icon = "lufy.png"; name = Jack; };
}
*/
NSDictionary *stuDict = stu.mj_keyValues;
/*
{
ID = 123;
bag = { name = "小書包"; price = 205; };
desc = handsome;
nameChangedTime = "2018-09-08";
nowName = jack;
oldName = rose;
}
*/
NSArray *dictArray = [User mj_keyValuesArrayWithObjectArray:userArray];
/*
(
{ icon = "lufy.png"; name = Jack; },
{ icon = "nami.png"; name = Rose; }
)
*/
把這兩種方式擺在一起看,結論其實很清楚:專案一旦成長、欄位一多,手写 KVC 很快就會難以維護;MJExtension 這類框架不只是省事,更是讓「網路層資料」與「業務邏輯」保持乾淨分離的關鍵。