iOS----解析网络json
一:当json以网址形式出现时:
(1)以前传统的解析json的方法:(代码存放位置是:在你需要解析的.m文件中)
NSError *error;
// 加载一个NSURL对象
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"这里是你的json的网址"]];
// 将请求的url数据放到NSData对象中
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// iOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中
NSDictionary *Dic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
// 字典中存放的数据也是字典型,从它里面通过键值取值
NSDictionary *Info = [Dic objectForKey:@“这里是你想要打印的json里边的某个值"];
// 打印出字典所存储数据
NSLog(@"%@",这里是你json想要打印出来的值);
(2)方法2:
// 加载一个NSURL对象
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://freegeoip.net/json/"]];
// 将请求的url数据放到NSData对象中
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// iOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中
NSString *ipDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
// weatherDic字典中存放的数据也是字典型,从它里面通过键值取值
NSDictionary *ipInfo = [ipDic objectForKey:@"ip"];
NSDictionary *ipInfo1=[ipDic objectForKey:@"country_code"];
NSDictionary *ipInfo2=[ipDic objectForKey:@"country_code"];
// 打印出weatherInfo字典所存储数据
NSDictionary *newDic=[ipDic objectFromJSONString];
NSLog(@"ipInfo字典里面的内容是--->%@",[newDic description]);
NSLog(@"ipInfo字典里面的内容是--->%@",[ipInfo1 description]);
NSLog(@"ipInfo字典里面的内容是--->%@",[ipDic objectForKey:@"country_code"]);
// 获取默认 Session
NSURLSession *session = [NSURLSession sharedSession];
// 创建 URL
NSURL *url = [NSURL URLWithString:@"http://freegeoip.net/json/"];
// 创建任务 task
NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// 获取数据后解析并输出
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
NSDictionary *info=[dic objectForKey:@"ip"];
NSLog(@"%@",[info description]);
NSDictionary *info2=[dic objectForKey:@"city"];
NSLog(@"%@",[info2 description]);
}];
// 启动任务
[task resume];
(2)方法2:
NSString *URLTmp1 = @"http:ip.taobao.com/service/getIpInfo.php?ip=myip";
NSString *URLTmp = [URLTmp1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData * resData = [NSData dataWithContentsOfURL:[NSURL URLWithString:URLTmp]];
if (resData) {
NSError *err;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:resData
options:NSJSONReadingMutableContainers
error:&err];
NSLog(@"dic = %@", dic);
NSDictionary *datadic = [[NSDictionary alloc] initWithDictionary:dic[@"data"]];
NSString *countryid = datadic[@"country_id"];