通常模型属性的名称必须与字典或数组的名称是一致的,否则则会出错。但因为字典或数组中的某些名称会与xcode冲突,所以我们可以通过MJExtension更换模型属性名称
在模型的.m文件实现
-(NSDictionary *)replacedKeyFromPropertyName
{
return @{@"ID":@"id",@"test":@"mytest"};
}
例子一:可以多重字典转换为模型,无论字典里面包括多少层字典
NSDictionary *dict = @{
@"id" : @"123424324",
@"text" : @"哈哈哈哈哈,天气真好",
@"user" : @{
@"idstr" : @"987766",
@"name" : @"搞笑排行榜",
@"profile_image_url" : @"http://abc.png"
}
};
HWStatus *status = [HWStatus objectWithKeyValues:dict];
例子二:
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) NSArray *books;
NSDictionary *dict = @{
@"name" : @"张三",
@"books" : @[
@{
@"name" : @"葵花1",
@"price" : @"10.6"
},
@{
@"name" : @"葵花2",
@"price" : @"10.9"
},
@{
@"name" : @"葵花3",
@"price" : @"17.6"
},
@{
@"name" : @"葵花4",
@"price" : @"14.4"
}
]
};
HWPerson *person = [HWPerson objectWithKeyValues:dict];
因为MJ不能知道NSAarry *books这个的模型是HWBooks,所以无法NSAarry *books转为模型。即我们要告知编译器。
只要我们在HWPerson.m文件中加上下面方法。
- (NSDictionary *)objectClassInArray
{
return @{@"books" : [HWBook class]};
}
一个字典对应一个模型,多个字典转化为多个模型,再将所有模型加入一个数组
原理:
//一个微博字典含有一个statuses数组,responseObject默认返回20条微博,所以dictArray有20组statuses数组
NSArray *dictArray = responseObject[@"statuses"];
//statuses数组里的数据是字典,所以将字典转为模型,再将所有模型加入一个数组,方便UITableViewCell使用
for (NSDictionary *dict in dictArray) {
WBStatuse *status = [WBStatuse objectWithKeyValues:dict];
[self.listArray addObject:status];
}
封装后:
NSArray *listArray = [MyModel objectArrayWithKeyValuesArray:responseObject[@"statuses"]];
例如数据是:
{
"statuses": [
{
"created_at": "Tue May 31 17:46:55 +0800 2011",
"id": 11488058246,
"text": "求关注。",
"source": "<a href="http://weibo.com" rel="nofollow">新浪微博</a>",
"favorited": false,
}
xxxx....
]
原文:http://my.oschina.net/u/2346786/blog/494821