0

我正在尝试制作从php文件获取数据的登录页面Json。它工作正常,直到我使用这句话[jsonData objectForKey:@"state"],出现异常。我试图制作另一个字典,比如之前的一些问题的答案。但没有什么对我有用。

输出 :

Response code : 200
Resonse ==> [{"state":"true"}]
JasonData  ({state = true})

然后异常

-[__NSarrayM objectforkey:]: unrecognized selector sent to instance

如果你能帮助我,我是 objctive-C 的新手。我会很开心

- (IBAction)loginClicked:(id)sender 
{

    @try 
{



    if([[txtUserName text] isEqualToString:@""] || [[txtPassword text] isEqualToString:@""] ) {
        [self alertStatus:@"Please enter both Username and Password" :@"Login Failed!"];
    } else {
        NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@",[txtUserName text],[txtPassword text]];
        NSLog(@"PostData: %@",post);

        NSURL *url = [NSURL URLWithString:@"http://localhost/services/pages/login.php"]; 


        NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

        NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:url];
        [request setHTTPMethod:@"POST"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:postData];
        NSError *error = [[NSError alloc] init];
        NSHTTPURLResponse *response = nil;
        NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

        NSLog(@"Response code: %d", [response statusCode]);
        if ([response statusCode] >=200 && [response statusCode] <300)
        {
            NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
            NSLog(@"Response ==> %@", responseData);                    

            SBJsonParser *jsonParser = [SBJsonParser new];
            NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
            NSLog(@"%@",jsonData);

            NSLog(@"%@",[jsonData objectForKey:@"state"]);
            NSString *state = [(NSString*) [jsonData objectForKey:@"state"] lowercaseString ];
            NSLog(@"%@", state);
            if([state isEqualToString:@"true"])
            {
                NSLog(@"Login SUCCESS");
                [self alertStatus:@"Logged in Successfully." :@"Login Success!"];

            }
            else 
            {

                NSString *error_msg = (NSString *) [jsonData objectForKey:@"error_message"];
                [self alertStatus:error_msg :@"Login Failed!"];
            }


        } 
        else 
        {
            if (error) NSLog(@"Error: %@", error);
            [self alertStatus:@"Connection Failed" :@"Login Failed!"];
        }
    }
}
@catch (NSException * e) 
{
    NSLog(@"Exception: %@", e);
    [self alertStatus:@"Login Failed." :@"Login Failed!"];
}
4

1 回答 1

3

网络服务器返回的 JSON 数据似乎是 anNSArray和 not NSDictionary。你可以在这里检查,

id jsonData = [jsonParser objectWithString:responseData error:nil];

if([jsonData isKindOfClass:[NSDictionary class]]) {
    NSLog(@"Dictionary");
}
else if([jsonData isKindOfClass:[NSArray class]]) {
    NSLog(@"Array");
}

您的代码崩溃,因为您假设解析的响应为NSDictionary并传递该objectForKey:方法。作为一个NSArray它无法识别此方法并引发异常。

现在,如果它是NSArray一本里面有一本字典,你可以读它如下,

[[jsonData objectAtIndex:0] objectForKey:@"state"];

希望有帮助!

于 2013-09-24T08:00:52.333 回答