HTTP请求和JSON解析与组装

本文介绍了iOS开发中JSON文件的解析方法及使用NSURLConnection和NSURLSession进行POST与GET网络请求的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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" 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;

                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

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值