无法解析NSURLConnection响应中的JSON数据

时间:2012-08-28 09:29:45

标签: iphone ios json web-services nsdictionary

我收到了以下表单的服务器响应:

results are:{
    AverageMark = 40;
    "Grade A" = 10;
    "Grade B" = 20;
    "Grade C" = 30;
    "Grade D" = 20;
    MaxMark = 99;
    MinMark = 44;
    ProfileGrade = "";
    ProfileMark = 1;
}

但是我无法将响应数据保存到数组中。 这是我在 didReceiveResponse

中的代码
    {    
        NSString *jsonString = [[NSString alloc] initWithString:responseData];
        NSArray *jsonResults = [jsonString JSONValue];
        NSLog(@"results are:%@",jsonResults); //this log is shown above
        for (int i=0; i<[jsonResults count]; i++)
        {
            NSDictionary *AllData=(NSDictionary *)[jsonResults objectAtIndex:i]; //Program is crashing here--//
            NSMutableArray  *DataArray=[[NSMutableArray alloc]init];
            NSString *avgMarkString;
            avgMarkString=(NSString *)[AllData objectForKey:@"MaxMark"];
            [DataArray addObject:avgMarkString];
        }
    }

我想将响应数据保存到名为“DataArray”的数组中。但该计划正在崩溃。 我做错了什么?

3 个答案:

答案 0 :(得分:1)

这不是json,试着看看这个http://json.org/example.html

答案 1 :(得分:1)

鉴于JSON响应无效。验证您的JSON响应here

答案 2 :(得分:1)

您可能还没有-connection:didReceiveResponse:中的完整数据。创建类型为NSMutableData的实例变量或属性,并初始化数据ivar或属性 -connection:didReceiveResponse:如果你得到一个有效的statusCode(200-299之间应该没问题)。在appendData:委托方法中对数据对象使用-connection:didReceiveData:。最后在-connectionDidFinishLoading:中,数据已完成,可以解析为JSON。

或者您可以使用AFNetworking库。该库有一些处理XML,JSON,图像等的便捷方法......

阅读以下页面,了解AFNetworking的功能:http://engineering.gowalla.com/2011/10/24/afnetworking/


我自己的一个项目的一些示例代码,使用NSURLConnectionDelegate方法使用队列进行下载。对于某些块“回调”,URL Request对象是NSURLConnection的自定义子类:

#pragma mark - URL connection delegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;

    NSRange range = NSMakeRange(200, 99);
    if (NSLocationInRange(httpResponse.statusCode, range));
    {
        self.data = [[NSMutableData alloc] init];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_data appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // inform caller that download is complete, provide data ...

    if (_request.completionHandler)
    {
        _request.completionHandler(_data, nil);
    }

    [self removeRequest:_request];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    DLog(@"%@", error);

    // inform caller that download failed, provide error ...

    if (_request.completionHandler)
    {
        _request.completionHandler(nil, error);
    }

    [self removeRequest:_request];
}