1.在模型类中定义属性
属性名需要和JSON文件中key值保持一致
@interface WBCityInfoModel : NSObject
/// 城市名
@property (nonatomic, copy) NSString *name;
/// id
@property (nonatomic, copy) NSString *idName;
注意:属性名与系统重名,需要在.m文件中调用
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
// jsonModel属性与系统重名
if ([key isEqualToString:@"id"]) {
_idName = value;
}
}
2.导入头文件 #import “YYModel.h”
在viewController定义一个数组属性
// 模型数组保存解析后的模型数据
@property (nonatomic, strong) NSArray *modelArray;
3.加载数据(这里使用YYModel)
#pragma mark - 加载数据
- (void)loadCitysData {
NSString *url = [[NSBundle mainBundle]URLForResource:@"citysData.json" withExtension:nil];
//加载JSON文件
NSData *data = [NSData dataWithContentsOfURL:url];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
// YYModel实现字典数组转模型数组
self.modelArray = [NSArray yy_modelArrayWithClass:[WBCityInfoModel class] json:dict];
// 回到主线程刷新UI
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self.tableView reloadData];
}];
}
结果: