0

次の形式のサーバー応答を取得しています。

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」という配列に保存したい。しかし、プログラムはクラッシュしています。私は何を間違っていますか?

4

3 に答える 3

1

にはまだ完全なデータがない可能性があります-connection:didReceiveResponse:。有効なstatusCodeを取得した場合は、そのタイプのインスタンス変数またはプロパティを作成しNSMutableData、データivarまたはプロパティを初期化します
-connection:didReceiveResponse:(200〜299で問題ありません)。デリゲートメソッドappendData:のデータオブジェクトで使用します。-connection:didReceiveData:最後に -connectionDidFinishLoading:、データが完成し、JSONに解析できます。

または、 AFNetworkingライブラリを使用することもできます。ライブラリには、XML、JSON、画像などを処理するための便利なメソッドがいくつかあります。

次のページを読んで、AFNetworkingの機能の概要を確認してください。http://engineering.gowalla.com/2011/10/24/afnetworking/


NSURLConnectionDelegateメソッドを使用してキューを使用してダウンロードするための私自身のプロジェクトの1つからのサンプルコード。URLリクエストオブジェクトは、一部のブロック「コールバック」の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];
}
于 2012-08-28T10:06:37.720 に答える
1

それはjsonではありません。これを見てみてくださいhttp://json.org/example.html

于 2012-08-28T09:37:51.070 に答える
1

指定された JSON 応答は無効です。ここでJSON レスポンスを検証します。

于 2012-08-28T09:48:06.930 に答える