开源第三方地址: https://github.com/icanzilb/JSONModel
- 1 model 创建
#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多级映射
@property (nonatomic, strong) NSArray *scoreArray;// model 嵌套数组
@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数组
其他
model 属性 不仅限于 NSString类型。
model 可以 设置 ignores