GitHub原文:https://github.com/ibireme/YYModel
或者直接打開.h文件查看如何使用。
說白了,
就是Json-Model-Dic三者相互轉化,並處理了null(轉化爲nil或者0)。
重點:
這是一個NSObject的Category,無須繼承,可以直接使用!
**--NSObject的方法--**
1.json、dic轉model(用於解析)
+ (nullable instancetype)yy_modelWithJSON:(id)json;
+ (nullable instancetype)yy_modelWithDictionary:(NSDictionary *)dictionary;
2.model轉json(用於提交數據)
- (nullable id)yy_modelToJSONObject;
- (nullable NSString *)yy_modelToJSONString;
3.打印model對象 (用於調試)
- (NSString *)yy_modelDescription;
**-- NSArray類方法 --**
@interface NSArray (YYModel)
//cls:Model類
//json:後臺的json數據
+ (nullable NSArray *)yy_modelArrayWithClass:(Class)cls json:(id)json;
例子:
NSArray *array = [NSArray yy_modelArrayWithClass:[ConsumeModel class] json:result.response[@"list"]];
其中,參數list是包含多個字典的大數組(json格式)
返回的是包含多個model的數組
我的技巧
1.Model 屬性名和 JSON 中的 Key 不相同, 比如後臺給你“id”。
// 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;//自定義的id
@end
@implementation Book
//If the key in JSON/Dictionary does not match to the model's property name, implements this method and returns the additional(額外的) mapper.
+ (NSDictionary *)modelCustomPropertyMapper {
return @{@"name" : @"n",
@"page" : @"p",
@"desc" : @"ext.desc",
@"bookID" : @"id"};
}
@end
2.在後臺Json轉化爲自定義的model後,如果想要對數據進行後續處理:
//If the model implements this method, it will be called at the end of
//`+modelWithJSON:`, `+modelWithDictionary:`, `-modelSetWithJSON:` and `-modelSetWithDictionary:`.
// If this method returns NO, the transform process will ignore this model.
- (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic;
例子:
- (BOOL)modelCustomTransformToDictionary:(NSMutableDictionary *)dic {
//code...
//dic[@"字段名"], 即可獲取某個值, 自己處理後, 付給model。
//時間戳轉化爲NSDate、求出文字高度...
return YES;
}
3.對於後臺的數據,如果需要處理“容器類”或者“大model包含小model”,直接參考GitHub原文做法更佳。
有個小demo可以看一下https://github.com/walkertop/YYModel—Demo
備註:
總之json與model與字典間的轉化,都可以使用YYModel。