IOS开发之POST和JSON处理
最近在开发IOS中,用到了POST数据到服务器,并将返回的JSON格式数据进行处理。这里使用的是JSON库是JSON-framwork
1 -(IBAction)JsonConvert:(id)sender 2 { 3 NSString *urlAsString = @"http://192.168.1.8/ajax/SInfo.ashx"; 4 urlAsString = [urlAsString stringByAppendingString:@"?param1=First"]; 5 urlAsString = [urlAsString stringByAppendingString:@"¶m2=Second"]; 6 NSURL *url = [NSURL URLWithString:urlAsString]; 7 8 NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url]; 9 [urlRequest setTimeoutInterval:30.0f]; 10 [urlRequest setHTTPMethod:@"POST"]; 11 12 NSString *body = @"bodyParam1=BodyValue1&bodyParam2=BodyValue2"; 13 [urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]]; 14 NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 15 16 [NSURLConnection 17 sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response,NSData *data, NSError *error) 18 { 19 if ([data length] >0 && error == nil){ 20 NSError * error; 21 NSMutableDictionary * root = [[CJSONDeserializer deserializer] deserialize:data error:&error]; 22 NSMutableArray *rows = [root objectForKey:@"rows"]; //获取需要循环的记录 23 NSString *str = [root objectForKey:@"total"]; 24 NSLog(@"总记录数::%@",str); 25 for(NSMutableDictionary *row in rows) 26 { 27 NSString *SchoolNo = [row objectForKey:@"SchoolNo"]; 28 NSLog(@"学校编号:%@",SchoolNo); 29 } 30 31 32 33 } 34 else if ([data length] == 0 && error == nil){ 35 NSLog(@"Nothing was downloaded."); 36 } 37 38 else if (error != nil){ 39 NSLog(@"Error happened = %@", error); 40 } 41 42 }]; 43 44 45 }