HTTP request and JSON parsing and assembly

JSON and XML are often used in development. The last time I asked my colleague whether the request for xml designed by ios existed, the question and answer is about to be eliminated, and the use of xml in android is also very small.

 

Parse local json file

 

{
    "settingView":"showContent",
    "mainViewModelData": [
                          {
                          "contenttitle": "Map",
                          "contentPage": "",
                          "state": "1"
                          },
                          {
                          "contenttitle": "Voice Search",
                          "contentPage": "",
                          "state": "1"
                          },
                          {
                          "contenttitle": "Push message",
                          "contentPage": "",
                          "state": "1"
                          },
                          {
                          "contenttitle": "QR code",
                          "contentPage": "",
                          "state": "1"
                          },
                          {
                          "contenttitle": "Image loading",
                          "contentPage": "",
                          "state": "1"
                          },
                          {
                          "contenttitle": "Bluetooth",
                          "contentPage": "",
                          "state": "1"
                          },
                          {
                          "contenttitle": "NFC",
                          "contentPage": "",
                          "state": "1"
                          },
                          {
                          "contenttitle": "声纹",
                          "contentPage": "",
                          "state": "1"
                          },
                          {
                          "contenttitle": "Face Recognition",
                          "contentPage": "",
                          "state": "1"
                          },
                          {
                          "contenttitle": "Video image",
                          "contentPage": "",
                          "state": "1"
                          }
                          ]
}

 

 

parsing;

 

#pragma mark--json parsing class
-(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 custom model stores parsed data
 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];
            }
        }

Parsing result:

2016-03-20 18:02:14.195 UIControlStart[923:53112] showContent= map ,contentPage=

2016-03-20 18:02:14.196 UIControlStart[923:53112] showContent= Voice Search , contentPage=

2016-03-20 18:02:14.197 UIControlStart[923:53112] showContent= Push message , contentPage=

2016-03-20 18:02:14.197 UIControlStart[923:53112] showContent= QR code ,contentPage=

2016-03-20 18:02:14.198 UIControlStart[923:53112] showContent= image loading , contentPage=

2016-03-20 18:02:14.198 UIControlStart[923:53112] showContent= Bluetooth ,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= Face Recognition ,contentPage=

2016-03-20 18:02:14.201 UIControlStart[923:53112] showContent= Video image ,contentPage= 

 

 

 

URLConnection request data

 

Commom *comom=[[Commom alloc]init];
    NSMutableDictionary *dictionary=[[NSMutableDictionary alloc]init];
    [dictionary setObject:@"苏州市" forKey:@"a"];
    //http://gc.ditu.aliyun.com/geocoding?a=Suzhou City
    [comom commomRequestPOSTURLAndParams:@"http://gc.ditu.aliyun.com/geocoding" andRequestParams:(NSMutableDictionary *) dictionary];


#pragma mark--//post request network
-(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) {//Determine whether there are parameters
            
                    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";
            //The sending must be set here, this place encapsulates the dictionary in json format
            //                [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

// request network
    Commom *comom=[[Commom alloc]init];
    NSMutableDictionary *dictionary=[[NSMutableDictionary alloc]init];
    [dictionary setObject:@"苏州市" forKey:@"a"];
    //http://gc.ditu.aliyun.com/geocoding?a=Suzhou City
    [comom commomRequestPOSTURLAndParams:@"http://gc.ditu.aliyun.com/geocoding" andRequestParams:(NSMutableDictionary *) dictionary];


#pragma mark--//post request network
-(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) {//Determine whether there are parameters
//                    
//                    dataParms= [NSJSONSerialization dataWithJSONObject:parmas options:NSJSONWritingPrettyPrinted error:nil];
//                    NSLog(@"dataParms=%@",dataParms);
//                    
//                }
//                
//                NSURL *requestAddress= [[NSURL alloc]initWithString:url];
// //Create a Session object
//                NSURLSession *session=[NSURLSession sharedSession];
//                
//                NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:requestAddress];
//                request.HTTPMethod=@"POST";
// //Send here must be set, this place encapsulates the dictionary in json format
//                //                [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 request data=%@",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) {//Determine whether there are parameters
                
                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"]]);
        
            //Create a Session object
            NSURLSession *session=[NSURLSession sharedSession];
            
            
            NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:requestAddress];
            request.HTTPMethod=@"POST";
            //The sending must be set here, this place encapsulates the dictionary in json format
            //                [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 request data=%@",dict);
                NSLog(@"lat=%@",dict[@"lat"]);
                NSLog(@"lon=%@",dict[@"lon"]);
                
            }];
            
            
            [sessionTask resume];
            
        });
    });
    
    
}

  result:

2016-03-20 18:02:18.200 UIControlStart[923:53294] post request data = {

    address = "";

    alevel = 4;

    cityName = "";

    years = "39.90403";

    level = "-1";

    lon = "116.40752";

}

2016-03-20 18: 02: 18.201 UIControlStart [923: 53294] years = 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=Suzhou City
    [comom commomRequestGETURLAndParams:@"http://mobile.weather.com.cn/data/forecast/101010100.html?_=1381891660081" andRequestParams:(NSMutableDictionary *) dictionary];



#pragma mark--//get request network
-(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 data=%@",dic);
                    
                    NSDictionary *dictc=dic[@"c"];
                    
                    NSLog(@"dictc 的c1=%@",dictc[@"c1"]);
                    
                }];
                
                [dataTask resume];
                
            });
            
        });
        
    }

}

 result:

2016-03-20 18:07:22.172 UIControlStart[936:57551] get data = {

    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

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326982774&siteId=291194637