解析JSON响应

时间:2013-02-18 15:56:33

标签: ios json afnetworking

我正在使用AFJSONRequestOperation来请求远程API:

 NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

        //Remove the SVProgressHUD view
        [SVProgressHUD dismiss];

        //Check for the value returned from the server

        NSData *jsonData = [JSON dataUsingEncoding:NSUTF8StringEncoding];//This line cause crash
        NSArray *arr = [NSJSONSerialization JSONObjectWithData:jsonData
                                                       options:0
                                                         error:nil];
        loginDic=[[NSDictionary alloc]init];
        loginDic=[arr objectAtIndex:0];
        NSLog(@"%@",loginDic);

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

        NSLog(@"Request Failed with Error: %@", [error.userInfo objectForKey:@"NSLocalizedDescription"]);
    }];
    [operation start];
    [SVProgressHUD showWithStatus:@"Loading"];

然而,应用程序崩溃了,我收到了这个错误:

[__NSCFDictionary dataUsingEncoding:]: unrecognized selector sent to instance

这是返回的JSON对象的NSLog

 Result =     (
                {
            operation = 5;
            result = 1;
        }
    );

我错过了什么,因为我认为我没有正确解析JSON对象。请纠正我。

2 个答案:

答案 0 :(得分:1)

您在成功块中获得的对象已由AFJSONRequestOperation解析。 在你的情况下,你得到一个NSDictionary对象。

您可以使用isKindofClass - 方法检查对象的类:

if ([JSON isKindOfClass:[NSDictionary class]]) {
   NSDictionary* dict = (NSDictionary*)JSON;
   ...
}

答案 1 :(得分:1)

看起来AFJSONRequestOperation正在为您将JSON反序列化为字典,然后您尝试再次执行此操作。 JSON是一个NSDictionary,但你正在调用NSString方法。

删除所有这些代码:

NSData *jsonData = [JSON dataUsingEncoding:NSUTF8StringEncoding];//This line cause crash
NSArray *arr = [NSJSONSerialization JSONObjectWithData:jsonData
                                                   options:0
                                                     error:nil];
loginDic=[[NSDictionary alloc]init];
loginDic=[arr objectAtIndex:0];

并将其替换为:

loginDic = [[JSON objectForKey:@"Result"] lastObject];

(这将在不检查数组边界的情况下安全地工作,但假设数组中只有一个元素。)

相关问题