JSON轉(zhuǎn)Model
id json —> dict —> Model
原理是用Runtime換取Model的屬性,生成映射表,然后objc_msgSend(…)調(diào)用setter方法賦值
你給我一個 Model 類,我會用 runtime 提供的各種函數(shù)來拿到你所有的屬性和對應(yīng)的get``set,判斷完相應(yīng)的類型以后,調(diào)用objc_msgSend(...)烟零。
// json轉(zhuǎn)模型
+ (instancetype)yy_modelWithJSON:(id)json;
// 模型轉(zhuǎn)字符串
- (NSString *)yy_modelToJSONString
// 字典轉(zhuǎn)模型
+ (instancetype)yy_modelWithDictionary:(NSDictionary *)dictionary ;
// 聲明數(shù)組宁炫、字典或者集合里的元素類型時要重寫
+ (nullable NSDictionary<NSString *, id> *)modelContainerPropertyGenericClass;
// 字典里的key值與模型的屬性值不一致要重復(fù) 需遵循<YYModel>
+ (nullable NSDictionary<NSString *, id> *)modelCustomPropertyMapper;
//黑名單 需遵循<modelPropertyBlacklis>
+ (nullable NSArray<NSString *> *)modelPropertyBlacklist;
//白名單 需遵循<modelPropertyWhitelist>
+ (nullable NSArray<NSString *> *)modelPropertyWhitelist;
最常用的就是下邊三個龙亲,用法:
1.字典轉(zhuǎn)模型,這個很簡單不說了悍抑;
// JSON:
{
"uid":123456,
"name":"Harry",
"created":"1965-07-31T00:00:00+0000"
}
// Model:
@interface User : NSObject
@property UInt64 uid;
@property NSString *name;
@property NSDate *created;
@end
@implementation User
@end
// 將 JSON (NSData,NSString,NSDictionary) 轉(zhuǎn)換為 Model:
User *user = [User yy_modelWithJSON:json];
// 將 Model 轉(zhuǎn)換為 JSON 對象:
NSDictionary *json = [user yy_modelToJSONObject];
2.聲明數(shù)組鳄炉、字典或者集合元素是要重寫:
+ (NSDictionary<NSString *,id> *)modelContainerPropertyGenericClass {
return @{
@"result":ResultModel.class,
};
}
3.字典里的key值與模型的屬性值不一致(這個經(jīng)常比如id等關(guān)鍵字)
Model 屬性名和 JSON 中的 Key 不相同
// JSON:
{
"n":"Harry Pottery",
"p": 256,
"ext" : {
"desc" : "A book written by J.K.Rowing."
},
"ID" : 100010
}
// Model:
@interface Book : NSObject
@property NSString *name;
@property NSInteger page;
@property NSString *desc;
@property NSString *bookID;
@end
@implementation Book
//返回一個 Dict,將 Model 屬性名對映射到 JSON 的 Key传趾。
+ (NSDictionary *)modelCustomPropertyMapper {
return @{@"name" : @"n",
@"page" : @"p",
@"desc" : @"ext.desc",
@"bookID" : @[@"id",@"ID",@"book_id"]};
}
@end
//如
+ (NSDictionary<NSString *,id> *)modelCustomPropertyMapper{
return @{@"pid":@"id"};
}
4迎膜、容器類屬性
@class Shadow, Border, Attachment;
@interface Attributes
@property NSString *name;
@property NSArray *shadows; //Array<Shadow>
@property NSSet *borders; //Set<Border>
@property NSMutableDictionary *attachments; //Dict<NSString,Attachment>
@end
@implementation Attributes
// 返回容器類中的所需要存放的數(shù)據(jù)類型 (以 Class 或 Class Name 的形式)。
+ (NSDictionary *)modelContainerPropertyGenericClass {
return @{@"shadows" : [Shadow class],
@"borders" : Border.class,
@"attachments" : @"Attachment" };
}
@end
6浆兰、黑名單與白名單
@interface User
@property NSString *name;
@property NSUInteger age;
@end
@implementation Attributes
// 如果實現(xiàn)了該方法磕仅,則處理過程中會忽略該列表內(nèi)的所有屬性
+ (NSArray *)modelPropertyBlacklist {
return @[@"test1", @"test2"];
}
// 如果實現(xiàn)了該方法珊豹,則處理過程中不會處理該列表外的屬性。
+ (NSArray *)modelPropertyWhitelist {
return @[@"name"];
}
@end