@interface JSONModel :NSObject <AbstractJSONModelProtocol>
/创建一个新的模型实例,并初始化它的JSON文本参数使用UTF8编码
-(instancetype)initWithString:(NSString*)string error:(JSONModelError**)err;
//创建一个新的模型实例,并初始化它的JSON文本参数使用给定的编码
-(instancetype)initWithString:(NSString *)string usingEncoding:(NSStringEncoding)encoding error:(JSONModelError**)err;
-(instancetype)initWithDictionary:(NSDictionary*)dict error:(NSError **)err;
// 讲模型内容导出到字典
-(NSDictionary*)toDictionary;
// 导出所有模型到json数据,并返回
-(NSString*)toJSONString;
// 讲装有字典的数组一次实例化对应的模型存在数组里
+(NSMutableArray*)arrayOfModelsFromDictionaries:(NSArray*)array;
// 将装有模型的数组中模型数据转为字典存入数组
+(NSMutableArray*)arrayOfDictionariesFromModels:(NSArray*)array;
-(NSString*)indexPropertyName;
-(BOOL)isEqual:(id)object;
-(NSComparisonResult)compare:(id)object;
-(BOOL)validate:(NSError**)error;
+(JSONKeyMapper*)keyMapper;
+(void)setGlobalKeyMapper:(JSONKeyMapper*)globalKeyMapper;
// 如果Model中有多余的属性,不用考虑;
+(BOOL)propertyIsOptional:(NSString*)propertyName;
+(BOOL)propertyIsIgnored:(NSString*)propertyName;
@interface JSONKeyMapper :NSObject
// toModel将JSON键名转换为模型属性名 toJSON将模型属性名转换为一个JSON键
-(instancetype)initWithJSONToModelBlock:(JSONModelKeyMapBlock)toModel
modelToJSONBlock:(JSONModelKeyMapBlock)toJSON;
// 创建一个JSONKeyMapper实例,基于您提供的映射,在映射参数。使用JSON键名称作为键,你的JSONModel属性名称作为值。{ @“crazy_JSON_name”:@“myCamelCaseName”}
-(instancetype)initWithDictionary:(NSDictionary*)map;
// 讲下划线转换为驼峰命名方式
+(instancetype)mapperFromUnderscoreCaseToCamelCase;
下面两段代码都可以实现匹配
+(JSONKeyMapper*)keyMapper2 {
NSDictionary *dict =@{
@"address" :@"address",
@"author.header_img" :@"authorHeaderImage",
@"author.uid" :@"authorUserId",
@"author.username" :@"authorauthorUsername",
@"city" :@"city",
@"city_id" :@"cityId",
@"cover_img" :@"coverImg",
};
JSONKeyMapper *mapper = [[JSONKeyMapperalloc] initWithDictionary:dict];
return dict;
}
// 重写了影射规律
+(JSONKeyMapper*)keyMapper {
/* 注意JuhuiModel里面需要映射2种类型
1. 驼峰Camel命名规范
2. 把author.header_img和author_username要映射到JuhuiModel直接字段里面 */
JSONKeyMapper *mapper = [JSONKeyMappermapperFromUnderscoreCaseToCamelCase];
// 取得影射的blocks对象
JSONModelKeyMapBlock modelBlock = mapper.modelToJSONKeyBlock;
// 根据上述的重新创建映射条件
JSONKeyMapper *newMapper = [[JSONKeyMapperalloc] initWithJSONToModelBlock:nilmodelToJSONBlock:^NSString *(NSString *keyName) {
// 告诉我们映射规律
if ([keyNameisEqualToString:@"authorHeaderImage"]) {
return@"author.header_img";
} elseif ([keyName isEqualToString:@"authorUsername"]) {
return@"author.username";
} elseif ([keyName isEqualToString:@"authorUserId"]) {
return@"author.uid";
} elseif ([keyName isEqualToString:@"coverImage"]) {
return@"cover_img";
} elseif ([keyName isEqualToString:@"desc"]) {
return@"descript";
}
return modelBlock(keyName);
}];
return newMapper;
}
另外,使用时创建Model继承jsonmodel,根据项目中需求,在model中重写jsonModel的方法 原文链接:https://www.f2er.com/json/289853.html