简体   繁体   中英

JSON isn't parsing in iOS?

I have the following code. My issue is I'm trying to parse a simple JSON response, but it doesn't seem to work. The JSON response looks like this:

{"response":"session_exists"}

I use the following to echo the JSON:

$json_output = array('response' => 'session_exists');

All I want to know is what response is equal to. It would be either session_exists or successful. What am I doing wrong?

I haven't worked with JSON before, so if anyone can help me out, it would really help me get going on this project.

Thanks!

- (IBAction)login:(id)sender {
    NSURL *url = [NSURL URLWithString:@"http://localhost/lookin_chill/Website/api/api_account.php?action=login&email=email@email.com&password=pass123"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    [connection start];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    data = [[NSMutableData alloc] init];
}

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

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

    responses = [NSJSONSerialization JSONObjectWithData:data options:nil error:nil];

    NSLog(@"%@", responses);

    NSLog(@"%@", [[responses objectAtIndex:0] objectForKey:@"response"]);
}

If your JSON looks like you say it does, then responses should be a dictionary, not an array, so you can't call objectAtIndex:0 on it. The log should be:

NSLog(@"%@", [responses objectForKey:@"response"]);

Alec i just tested it with my parser and works well just convert your response to NSDictionary and try this i just tried it with the string

         NSString *string =@"{\"response\":\"session_exists\"}";
         JSONDecoder *value =[string objectFromJSONString];
         NSDictionary *dictionary = (NSDictionary *)value;
         NSLog(@"value %@",[dictionary objectForKey:@"response"]);

And the value is

           session_exists

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM