開源第三方地址: https://github.com/icanzilb/JSONModel
- 1 model 創(chuàng)建
#import "JSONModel.h"
// 次model
@interface ScoreModel : JSONModel
@property (nonatomic, strong) NSString *english;
@property (nonatomic, strong) NSString *chinese;
@end
// 主model
@interface UserModel : JSONModel
@property (nonatomic, strong) NSString *name; // 一般
@property (nonatomic, strong) ScoreModel *scores; // model 嵌套 model
@property (nonatomic, strong) NSString *eng_score; // 獲取 scores 中的 英語成績,model多級(jí)映射
@property (nonatomic, strong) NSArray *scoreArray;// model 嵌套數(shù)組
@end
- 2 model 屬性 可空 或 不存在
#import "UserModel.h"
@implementation ScoreModel
+ (BOOL)propertyIsOptional:(NSString *)propertyName{
return YES; //
}
@end
@implementation UserModel
+ (BOOL)propertyIsOptional:(NSString *)propertyName{
return YES;
}
- 3 修改 映射 路徑,
+(JSONKeyMapper*)keyMapper{
// 映射路徑 : 屬性名
return [[JSONKeyMapper alloc] initWithDictionary:@{
@"scores.english": @"eng_score"
}];
}
- 4 舉例
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 alloc] initWithDictionary:dict error:nil];
NSLog(@"%@",model.name);// 正常的 字典
NSLog(@"%@",model.scores.english);// 嵌套 model
NSLog(@"%@",model.eng_score);// 修改映射路徑
NSLog(@"%@",model.scoreArray[0]);// 嵌套 model數(shù)組
其他
model 屬性 不僅限于 NSString類型。
model 可以 設(shè)置 ignores