HTTP请求和JSON解析与组装
json和xml在开发中回经常使用到,上次问同事ios设计到xml的请求是否存在,问答是快被淘汰了,xml在android的使用也很少
解析本地json文件
{ "settingView":"showContent", "mainViewModelData": [ { "contenttitle": "地图", "contentPage": "", "state": "1" }, { "contenttitle": "语音搜索", "contentPage": "", "state": "1" }, { "contenttitle": "推送消息", "contentPage": "", "state": "1" }, { "contenttitle": "二维码", "contentPage": "", "state": "1" }, { "contenttitle": "图片加载", "contentPage": "", "state": "1" }, { "contenttitle": "蓝牙", "contentPage": "", "state": "1" }, { "contenttitle": "NFC", "contentPage": "", "state": "1" }, { "contenttitle": "声纹", "contentPage": "", "state": "1" }, { "contenttitle": "脸部识别", "contentPage": "", "state": "1" }, { "contenttitle": "视频图片", "contentPage": "", "state": "1" } ] }
解析;
#pragma mark--json解析类 -(NSDictionary *)getJSONToString{ NSData *dataJSON=[NSData dataWithContentsOfFile:[[NSBundle mainBundle]pathForResource:main_json ofType:main_type]]; NSDictionary *dictionary=[NSJSONSerialization JSONObjectWithData:dataJSON options:0 error:nil]; return dictionary; }
//SettingViewBean自定义的model存储解析的数据 NSMutableArray *data=[[NSMutableArray alloc]init]; NSDictionary *dic =[self getJSONToString]; id dicArray=dic[@"mainViewModelData"]; for (id dic in dicArray) { if ([@"1" isEqualToString:dic[@"state"]]) { SettingViewBean *svb=[[SettingViewBean alloc]initWith:dic[@"contenttitle"] andContentPage:dic[@"contentPage"]]; [data addObject:svb]; [svb release]; } }
解析结果:
2016-03-20 18:02:14.195 UIControlStart[923:53112] showContent=地图,contentPage=
2016-03-20 18:02:14.196 UIControlStart[923:53112] showContent=语音搜索,contentPage=
2016-03-20 18:02:14.197 UIControlStart[923:53112] showContent=推送消息,contentPage=
2016-03-20 18:02:14.197 UIControlStart[923:53112] showContent=二维码,contentPage=
2016-03-20 18:02:14.198 UIControlStart[923:53112] showContent=图片加载,contentPage=
2016-03-20 18:02:14.198 UIControlStart[923:53112] showContent=蓝牙,contentPage=
2016-03-20 18:02:14.198 UIControlStart[923:53112] showContent=NFC,contentPage=
2016-03-20 18:02:14.199 UIControlStart[923:53112] showContent=声纹,contentPage=
2016-03-20 18:02:14.200 UIControlStart[923:53112] showContent=脸部识别,contentPage=
2016-03-20 18:02:14.201 UIControlStart[923:53112] showContent=视频图片,contentPage=
URLConnection请求数据
Commom *comom=[[Commom alloc]init]; NSMutableDictionary *dictionary=[[NSMutableDictionary alloc]init]; [dictionary setObject:@"苏州市" forKey:@"a"]; //http://gc.ditu.aliyun.com/geocoding?a=苏州市 [comom commomRequestPOSTURLAndParams:@"http://gc.ditu.aliyun.com/geocoding" andRequestParams:(NSMutableDictionary *) dictionary]; #pragma mark--//post请求网络 -(void)commomRequestPOSTURLAndParams:(NSString*)url andRequestParams:(NSMutableDictionary*)parmas{ __block NSData *dataParms; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ dispatch_async(dispatch_get_main_queue(), ^{ if ([parmas count]!=0) {//判断是否存在参数 dataParms= [NSJSONSerialization dataWithJSONObject:parmas options:NSJSONWritingPrettyPrinted error:nil]; NSLog(@"dataParms = %@,str = %@",dataParms,[[NSString alloc] initWithData:dataParms encoding:NSUTF8StringEncoding]); } NSURL *requestAddress= [[NSURL alloc] initWithString:url]; NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:requestAddress]; request.HTTPMethod=@"POST"; //此处发送一定要设置,这个地方把字典封装为json格式 // [request setValue:@"application/jason" forHTTPHeaderField:@"Content-Type"]; request.HTTPBody=dataParms; [request setValue:@"applocation/json" forHTTPHeaderField:@"Content-Type"]; NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { NSLog(@"%@ \n -----> %@",data,[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); NSLog(@"%@",connectionError); NSLog(@"fdlkasl"); }]; }); }); }
3,NSURLSession POST
//请求网络 Commom *comom=[[Commom alloc]init]; NSMutableDictionary *dictionary=[[NSMutableDictionary alloc]init]; [dictionary setObject:@"苏州市" forKey:@"a"]; //http://gc.ditu.aliyun.com/geocoding?a=苏州市 [comom commomRequestPOSTURLAndParams:@"http://gc.ditu.aliyun.com/geocoding" andRequestParams:(NSMutableDictionary *) dictionary]; #pragma mark--//post请求网络 -(void)commomRequestPOSTURLAndParams:(NSString*)url andRequestParams:(NSMutableDictionary*)parmas{ // __block NSData *dataParms; // // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // // dispatch_async(dispatch_get_main_queue(), ^{ // // if ([parmas count]!=0) {//判断是否存在参数 // // dataParms= [NSJSONSerialization dataWithJSONObject:parmas options:NSJSONWritingPrettyPrinted error:nil]; // NSLog(@"dataParms=%@",dataParms); // // } // // NSURL *requestAddress= [[NSURL alloc]initWithString:url]; // //创建Session对象 // NSURLSession *session=[NSURLSession sharedSession]; // // NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:requestAddress]; // request.HTTPMethod=@"POST"; // //此处发送一定要设置,这个地方把字典封装为json格式 // // [request setValue:@"application/jason" forHTTPHeaderField:@"Content-Type"]; // [request setValue:@"applocation/json" 4000 forHTTPHeaderField:@"Content-Type"]; // // request.HTTPBody=dataParms; // // NSURLSessionTask *sessionTask= [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { // // // // NSMutableDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; // // NSLog(@"get请求数据=%@",dict); // // }]; // // // [sessionTask resume]; // // }); // }); __block NSData *dataParms; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ dispatch_async(dispatch_get_main_queue(), ^{ if ([parmas count]!=0) {//判断是否存在参数 dataParms= [NSJSONSerialization dataWithJSONObject:parmas options:NSJSONWritingPrettyPrinted error:nil]; NSLog(@"dataParms=%@ ",[[NSString alloc] initWithData:dataParms encoding:NSUTF8StringEncoding]); } NSURL *requestAddress= [[NSURL alloc] initWithString:url]; NSLog(@"%@",[NSString stringWithFormat:@"%@?a=%@",url,[parmas objectForKey:@"a"]]); //创建Session对象 NSURLSession *session=[NSURLSession sharedSession]; NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:requestAddress]; request.HTTPMethod=@"POST"; //此处发送一定要设置,这个地方把字典封装为json格式 // [request setValue:@"application/jason" forHTTPHeaderField:@"Content-Type"]; [request setValue:@"applocation/json" forHTTPHeaderField:@"Content-Type"]; request.HTTPBody=dataParms; NSURLSessionTask *sessionTask= [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSMutableDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSLog(@"post请求数据=%@",dict); NSLog(@"lat=%@",dict[@"lat"]); NSLog(@"lon=%@",dict[@"lon"]); }]; [sessionTask resume]; }); }); }
结果:
2016-03-20 18:02:18.200 UIControlStart[923:53294] post请求数据={
address = "";
alevel = 4;
cityName = "";
lat = "39.90403";
level = "-1";
lon = "116.40752";
}
2016-03-20 18:02:18.201 UIControlStart[923:53294] lat=39.90403
2016-03-20 18:02:18.201 UIControlStart[923:53294] lon=116.40752
4,NSURLSession GET
NSMutableDictionary *dictionary=[[NSMutableDictionary alloc]init]; [dictionary setObject:@"苏州市" forKey:@"a"]; http://gc.ditu.aliyun.com/geocoding?a=苏州市 [comom commomRequestGETURLAndParams:@"http://mobile.weather.com.cn/data/forecast/101010100.html?_=1381891660081" andRequestParams:(NSMutableDictionary *) dictionary]; #pragma mark--//get请求网络 -(void)commomRequestGETURLAndParams:(NSString*)url andRequestParams:(NSMutableDictionary*)parmas{ NSLog(@"parmas=%@",parmas); // __block NSData *dataParms; self = [super init]; if (self) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ dispatch_async(dispatch_get_main_queue(), ^{ NSURLSession *session=[NSURLSession sharedSession]; NSURL *requestAddress= [[NSURL alloc]initWithString:url]; NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:requestAddress]; request.HTTPMethod=@"GET"; NSURLSessionDataTask *dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSLog(@"get的数据=%@",dic); NSDictionary *dictc=dic[@"c"]; NSLog(@"dictc 的c1=%@",dictc[@"c1"]); }]; [dataTask resume]; }); }); } }
结果:
2016-03-20 18:07:22.172 UIControlStart[936:57551] get的数据={
c = {
c1 = 101010100;
c10 = 1;
c11 = 010;
c12 = 100000;
c13 = "116.391";
c14 = "39.904";
c15 = 33;
c16 = AZ9010;
c17 = "+8";
c2 = beijing;
c3 = "\U5317\U4eac";
c4 = beijing;
c5 = "\U5317\U4eac";
c6 = beijing;
c7 = "\U5317\U4eac";
c8 = china;
c9 = "\U4e2d\U56fd";
};
f = {
f0 = 201310121100;
f1 = (
{
fa = 01;
fb = 03;
fc = 10;
fd = 5;
fe = 0;
ff = 0;
fg = 0;
fh = 0;
fi = "06:21|17:40";
},
{
fa = 07;
fb = 07;
fc = 19;
fd = 12;
fe = 0;
ff = 0;
fg = 0;
fh = 0;
fi = "06:22|17:38";
},
{
fa = 02;
fb = 00;
fc = 15;
fd = 5;
fe = 8;
ff = 8;
fg = 3;
fh = 1;
fi = "06:23|17:37";
},
{
fa = 00;
fb = 00;
fc = 16;
fd = 4;
fe = 0;
ff = 0;
fg = 0;
fh = 0;
fi = "06:24|17:35";
},
{
fa = 00;
fb = 00;
fc = 18;
fd = 7;
fe = 0;
ff = 0;
fg = 0;
fh = 0;
fi = "06:25|17:34";
},
{
fa = 00;
fb = 01;
fc = 18;
fd = 8;
20000 fe = 0;
ff = 0;
fg = 0;
fh = 0;
fi = "06:26|17:32";
},
{
fa = 01;
fb = 01;
fc = 16;
fd = 6;
fe = 0;
ff = 0;
fg = 0;
fh = 0;
fi = "06:27|17:31";
}
);
};
}
2016-03-20 18:07:22.172 UIControlStart[936:57551] dictc 的c1=101010100
阅读更多
- cJSON学习练练手--解析与组装JSON数据
- 灵活组装Json的数据使用Gson的JsonParser和JsonReader解析Json详解例子
- ASIHttpRequest+SBJson完成Http请求,以及json数据解析
- Swift: 用Alamofire做http请求,用ObjectMapper解析JSON
- swift http请求返回json数据并解析
- 灵活组装Json的数据使用Gson的JsonParser和JsonReader解析Json详解例子
- Json数据的组装和解析
- C# 发送HTTP请求 C#解析Json格式
- Gson解析HTTP请求的响应json数据,Map/Bean
- android中Http请求及XML,JSON解析
- cocos2d-x 3.1.1 学习笔记[11] http请求 + json解析
- java解析和组装json以及一些方法的理解
- 基本HTTP请求+JSON解析+发送异步请求
- cocos2d-x 3.1.1 学习笔记[11] http请求 + json解析
- Json数据的组装和解析
- http请求和json解析
- Python操作小结(连接mysql、解析txt\json文件、crontab任务、http请求, 等等)
- c++ http请求,json解析
- http请求和json解析的截取字符串
- 灵活组装Json的数据使用Gson的JsonParser和JsonReader解析Json详解例子