json解析 本地文件和网上文件(通过接口)

来源:互联网 发布:进销存软件排行 编辑:程序博客网 时间:2024/05/17 00:18

json解析

对本地文件解析

NSString *path =[[NSBundle mainBundle] pathForResource:@“movielist” ofType:@“txt”];

// 第二个参数,制定一个容器来接收解析后的数据

NSMutableDictionary *dic =[NSJSONSerialization JSONObjectWithData:data option:NSJSONReadingMutableContainers error:nil];NSMutableArray *movieArr =[NSMutableArray array];    for (NSMutableDictionary *temp in dic[@"result"]) {        Movie *movie =[[Movie alloc] init];        [movie setValuesForKeysWithDictionary:temp];        [movieArr addObject:movie];        [movie release];    }

对网上文件的解析

原代码

NSString *strURL =@"http://api.map.baidu.com/place/v2/search?query=银行&region=大连&output=json&ak=6E823f587c95f0148c19993539b99295";
一个正常的URL地址是不允许有中文的,只能有数字, 26个英文字母的大小写,和一些特殊的符号,比如 &,%等,如果遇到带中文的URL,首先不它进行编码

原代码:

NSString *strEncode= [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

接下来,URL符合要求之后,就开始进行网络请求,网络请求分为三步

1.根据已经编好的URL,创建一个NSURL

NSURL *url =[NSURL URLWithString:strEncode];

2.发送一个请求

原代码:

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

3.返回我们要的数据,一个NSData对象

三个参数:第一个参数是刚刚创建的请求,第二个是返回的一个响应,第三个是错误信息

原代码

 NSURLResponse *response = nil;    NSError *error =nil;    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

对返回回来的数据, data进行json解析

把所有的银行名都打印出来
原代码:

NSMutableDictionary *dic =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];    for (NSDictionary *dic1 in dic[@"results"]) {        NSLog(@"%@",dic1[@"name"]);    }
0 0