最基本用法:
// 将字典转为模型
Person *p = [Person mj_objectWithKeyValues:dict2];
// 将 plist数据转成模型数组
NSArrar *models = [Person mj_objectArrayWithFile:@“xx.plist”];
// 将字典数组转成模型数组, 最常用
NSArrar *models = [Person mj_objectArrayWithKeyValuesArray:dict];
1 . 属性名和关键字冲突, 我们需要变更属性名, 比如 JSON 里是 id, 我们最好不要用 id, 又比如 discription, 和系统类重名了
NSDictionary *dict = @{
@"name":@"xiaofei",
@"age":@24,
@"id":@123456,
@"description":@"haoshuai"
};
这时候我们属性就不能命名 id, description 了, 得换一个
// person.h
@interface Person : NSObject
@property(nonatomic, strong) NSString * name;
@property(nonatomic, assign) NSInteger age;
@property(nonatomic, strong) NSString * descrip;
@property(nonatomic, strong) NSString *ID;
@end
光换名字不行, 我们得把换的名字和字典中的 key联系起来, 不然转换成模型后, 属性是没有值得
MJExtension 提供了一个+ mj_replacedKeyFromPropertyName的方法(该方法在模型中使用), 可以把原来字典中的 key 和你修改后的属性再关联起来, 你只要告诉它, 想把什么属性名替换为原来的那个 key
// person.m
- (NSDictionary *)mj_replacedKeyFromPropertyName
{
return @{
// 模型属性: JSON key, MJExtension 会自动将 JSON 的 key 替换为你模型中需要的属性
@“ID”?“id”,
@“descrip”?“description”,
};
}
2 .