//获取文件中的json数据
//JsonData 是文件名
//json 是文件后缀民
NSString *path=[[NSBundle mainBundle] pathForResource:@"JsonData" ofType:@"json"];
NSData *data=[[NSData alloc] initWithContentsOfFile:path];
//解析成字典
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
解析成对象放到数组中
if ([dic isKindOfClass:[NSDictionary class]]) {
//开始解析数据
_tableArray=[[NSMutableArray alloc]init];
NSArray *programmersArray=[dic objectForKey:@"programmers"];
//遍历数组对象
for (int i=0; i<programmersArray.count; i++) {
NSDictionary *authorDic=[programmersArray objectAtIndex:i];
NSString *firstName=[authorDic objectForKey:@"firstName"];
NSString *lastName=[authorDic objectForKey:@"lastName"];
NSString *email=[authorDic objectForKey:@"email"];
Author *author=[[Author alloc]init];
author.firstName=firstName;
author.lastName=lastName;
author.email=email;
[_tableArray addObject:author];
}
NSArray *musiciansArray=[dic objectForKey:@"programmers"];
//遍历数组对象
for (int i=0; i<musiciansArray.count; i++) {
NSDictionary *authorDic=[musiciansArray objectAtIndex:i];
NSString *firstName=[authorDic objectForKey:@"firstName"];
NSString *lastName=[authorDic objectForKey:@"lastName"];
NSString *email=[authorDic objectForKey:@"email"];
Author *author=[[Author alloc]init];
author.firstName=firstName;
author.lastName=lastName;
author.email=email;
[_tableArray addObject:author];
}
//解析根数据
NSArray *authorsArray=[dic objectForKey:@"authors"];
//遍历数组对象
for (int i=0; i<authorsArray.count; i++) {
NSDictionary *authorDic=[authorsArray objectAtIndex:i];
NSString *firstName=[authorDic objectForKey:@"firstName"];
NSString *lastName=[authorDic objectForKey:@"lastName"];
NSString *email=[authorDic objectForKey:@"email"];
Author *author=[[Author alloc]init];
author.firstName=firstName;
author.lastName=lastName;
author.email=email;
[_tableArray addObject:author];
}
}
Author 对象头文件
@interface Author : NSObject
@property (nonatomic,copy) NSString *firstName;
@property (nonatomic,copy) NSString *lastName;
@property (nonatomic,copy) NSString *email;
-(NSString *) getName;
@end
Author .m文件
@implementation Author
-(NSString *)getName{
return [NSString stringWithFormat:@"%@ %@",_lastName,_firstName];
}
@end
模版son
{"programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
]
}