開源第三方地址: https://github.com/CoderMJLee/MJExtension
- 1 model 創(chuàng)建
#import <Foundation/Foundation.h>
// 次model
@interface ScoreModel : NSObject
@property (nonatomic, strong) NSString *english;
@property (nonatomic, strong) NSString *chinese;
@end
// 主model
@interface UserModel : NSObject
@property (nonatomic, strong) NSString *name; // 一般
@property (nonatomic, strong) ScoreModel *scores; // model 嵌套 model
@property (nonatomic, strong) NSString *eng_score; // 獲取 scores 中的 英語(yǔ)成績(jī)婴梧,model多級(jí)映射
@property (nonatomic, strong) NSArray *scoreArray;// model 嵌套數(shù)組
@end
- 2 修改映射路徑
model.m 重寫
+ (NSDictionary *)mj_replacedKeyFromPropertyName{
// name 是 model 屬性 洛波,XM 是獲取數(shù)據(jù)中的真實(shí)key值。
// eng_score 是 model 屬性昨登,scores.english 是獲取數(shù)據(jù)中映射路徑(scores 是 UserModel 的屬性,english 是 ScoreModel 的屬性)
return @{@"name":@"XM",
@"eng_score":@"scores.english"};
}
/*
// 或者在 使用model之前添加塔猾,代替在 model.m 中 設(shè)置篙骡。
[UserModel mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
return @{@"name":@"XM",
@"eng_score":@"scores.english"};
}];
*/
- 3 簡(jiǎn)單使用,舉例
NSDictionary *dict = @{
@"name" : @"Jack",
@"address":@"浙大紫金港",
@"age" : @"20",
@"scores":@{@"english":@"99",@"chinese":@"133"},
@"scoreArray":@[@{@"english":@"99",@"chinese":@"133"},
@{@"english":@"98",@"chinese":@"134"},
@{@"english":@"97",@"chinese":@"135"}]
};
UserModel *model = [UserModel mj_objectWithKeyValues:dict];
NSLog(@"%@",model.name);// 一般 model
NSLog(@"%@",model.scores.english);// 嵌套model
NSLog(@"%@",model.eng_score);// 修改 映射
NSLog(@"%@",model.scoreArray[0]);// 嵌套 model 數(shù)組
其他
- 1 數(shù)組 model 直接 轉(zhuǎn)換
// 直接 通過(guò) 一般字典數(shù)組 轉(zhuǎn)換成 model 的數(shù)組丈甸。
NSArray *modelarr = [UserModel mj_objectArrayWithKeyValuesArray:testArray];
- 2 model 屬性 特殊處理
model.m 中
- (id)mj_newValueFromOldValue:(id)oldValue property:(MJProperty *)property{
// property 屬性名稱糯俗,oldValue 返回?cái)?shù)據(jù)
if ([property.name isEqualToString:@"name"]) {
if (oldValue == nil) {
return @"這個(gè)沒有返回哦";
}
} else if (property.type.typeClass == [NSDate class]) {
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"yyyy-MM-dd";
return [fmt dateFromString:oldValue];
}
return oldValue;
}
11