2

私は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

NSLog返される JSON オブジェクトは次のとおりです。

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

JSONオブジェクトを正しく解析していないと思うので、何か不足していますか? 私を修正してください。

4

2 に答える 2

1

成功ブロックで取得したオブジェクトは、 によって既に解析されていAFJSONRequestOperationます。あなたの場合、NSDictionary オブジェクトを取得します。

isKindofClass-メソッドを使用して、オブジェクトのクラスを確認できます。

if ([JSON isKindOfClass:[NSDictionary class]]) {
   NSDictionary* dict = (NSDictionary*)JSON;
   ...
}
于 2013-02-18T16:02:32.130 に答える
1

AFJSONRequestOperation が JSON を辞書に逆シリアル化しているように見えますが、もう一度実行しようとしています。JSONNSDictionary ですが、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];

(これは、配列の境界をチェックしなくても安全に機能しますが、配列に要素が 1 つしかないことを前提としています。)

于 2013-02-18T16:03:56.387 に答える