如何使用 AFNetworking 进行 json 解析

Posted

技术标签:

【中文标题】如何使用 AFNetworking 进行 json 解析【英文标题】:how to make json parsing with AFNetworking 【发布时间】:2014-01-17 06:16:28 【问题描述】:

您好,我正在尝试实施 AFNetworking 框架。我想使用 AFNetworking 框架检索 json 数据。但我不知道如何使用 AFNetworking 框架检索 json 数据。请任何人指导我。 这是我的代码:

-(void)ViewDidLoad



    userid=[[NSUserDefaults standardUserDefaults]valueForKey:@"user_id"];

    encryptpwd=[[NSUserDefaults standardUserDefaults]valueForKey:@"Encrypt_Psw"];

    id=[[NSUserDefaults standardUserDefaults]valueForKey:@"comm_id"];

    NSString *strJson=[NSString   stringWithFormat:@"userId=%@&encryptPassword=%@&commId=%@",userid,encryptpwd,id];

    NSString *strlength=[NSString stringWithFormat:@"%d",[strJson length]];

    NSURL *url=[NSURL URLWithString:@“My URL”];

    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];

   [request addValue:@"text/html" forHTTPHeaderField:@"Content-Type"];

   [request addValue:strlength forHTTPHeaderField:@"Content-Length"];

   NSData *requestData=[strJson dataUsingEncoding:NSUTF8StringEncoding];

   [request setHTTPBody:requestData];

   [request setHTTPMethod:@"Post"];

   [[NSURLConnection alloc]initWithRequest:request delegate:self];




- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response



     responseData=[[NSMutableData alloc]init];



- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data



    [responseData appendData:data];



- (void)connectionDidFinishLoading:(NSURLConnection *)connection



    [UIApplication sharedApplication].networkActivityIndicatorVisible=YES;

    NSError *err;

    NSString *strResponse=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];

    NSLog(@"response is %@",strResponse);

    dit=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&err];

    NSArray *arrResults = [dit valueForKey:@"class_mst"];

    listOfObjects = [NSMutableArray array];

    for(dictRes in arrResults)

    

         Attributes *at = [[Attributes alloc]init];

         at.classimage=[dictRes valueForKey:@"image_name"];

         at.classname=[dictRes valueForKey:@"class_title"];

         [listOfObjects addObject:at];

    

    [tableView reloadData];

 


 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error



     [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;

     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Internet Connection" message:@"Please ensure you have internet connection" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];

     [alert show];



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section



    return [listOfObjects count];



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath



     static NSString *identifier=@"cell";

     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

    if (cell == nil) 

    

         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];

    

    UIImageView *imageView =[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 300, 80)];

    imageView.tag = 100;

    [cell.contentView addSubview:imageView];

    UILabel *classtitle=[[UILabel alloc]initWithFrame:CGRectMake(5, 120, 200, 20)];

    classtitle.highlightedTextColor=[UIColor clearColor];

    classtitle.font=[UIFont systemFontOfSize:12.0];

    [cell.contentView addSubview:classtitle];

    Attributes *att = [listOfObjects objectAtIndex:indexPath.row];

    NSString *strf=att.classname;

    classtitle.text=strf;

    str=att.classimage;

    url=@“image URL”;

     UIImageView *cellImageView = [cell.contentView viewWithTag:100];

   // cellImageView.image = nil;

   if(str!=nil) 

   

        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);

       dispatch_async(queue, ^(void) 

       


            NSString *imageStr = [url stringByAppendingString:str];
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageStr]]];

            dispatch_async(dispatch_get_main_queue(), ^

            cellImageView.image = image;

       );

       );

    

    return cell;


【问题讨论】:

【参考方案1】:

您可以从以下链接导入 AFNetworking 库:https://github.com/AFNetworking/AFNetworking 并使用以下代码:

NSURL *url = [[NSURL alloc] initWithString:@"YOURURL"];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:@"POST"];
[request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
 NSString *strJson=[NSString stringWithFormat:@"userId=%@&encryptPassword=%@&commId=%@",userid,encryptpwd,id];
[request setHTTPBody:[strJson dataUsingEncoding:NSUTF8StringEncoding]];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) 
    NSDictionary *dict = [[NSDictionary alloc] initWithDictionary:JSON];

    NSArray *arrResults = [dict valueForKey:@"class_mst"];

    listOfObjects = [NSMutableArray array];

    for(dictRes in arrResults)

    

     Attributes *at = [[Attributes alloc]init];

     at.classimage=[dictRes valueForKey:@"image_name"];

     at.classname=[dictRes valueForKey:@"class_title"];

     [listOfObjects addObject:at];

   

   [tableView reloadData];

失败:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) ];

[operation start];

【讨论】:

感谢您的回复。根据我的代码剩余部分相同或我的代码中有任何更改。我的意思是 - (void)connectionDidFinishLoading:(NSURLConnection *)connection 这些部分相同或任何更改是那里? 我得到了错误,比如“使用未声明的标识符”这行代码..AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)。 ........ 什么类型的类导入了我的 .m 文件 传递参数的方式不正确。您应该决定是否将 JSON 作为内容或表单 urlencoded 参数传递。 @Shubham,我只得到了那行代码兄弟的错误。我是 importe #import "AFNetworking.h" @Shubham 我收到了类似“使用未声明的标识符 AFJsonRequestOperation”的错误【参考方案2】:

在 AFNetworking 中,您可以使用 AFJSONRequestOperation,它通过网络获取数据并给出经过解析的 json 响应。谢谢

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) 

            //it give parse json data
            NSDictionary *dict = [[NSDictionary alloc] initWithDictionary:JSON];

         failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) 

        ];

        [operation start];

【讨论】:

以上是关于如何使用 AFNetworking 进行 json 解析的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 AFNetworking 框架与 json 一起使用我自己的 api 登录我有令牌要传递但我现在不知道如何使用这些

AFNetworking 2 使用 AFHTTPRequestOperation 进行身份验证

如何使用 AFNetworking 在 http 中将 json 数据作为参数传递

如何使用 AFNetworking 在 iPhone 模拟器中通过 *** IP 地址进行连接?

如何使用 JSON 格式解析通过 AFNetworking 1.0 获得的响应

如何使用 AFNetworking-2.0 执行 JSON 编码的 GET 请求?