I am trying to learn how to parse JSON data so I can handle big databases. I wrote code to login into a website.
I have following JSON data from a successful login request:
JSON string : correct username and password [{"user_id":"7","first_name":"dada","last_name":"Kara","e_mail":"yaka@gmail","fullname":"Dada Kara","forum_username":"ycan"}]
and i use following code to parse but it doesnt parse it
-(IBAction)loginButton:(id)sender{
NSString *username = usernameTextfield.text;
NSString *password = passwordTextfield.text;
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:kPostUrl]];
[request setHTTPMethod:@"POST"];
NSString *post =[[NSString alloc] initWithFormat:@"e_mail=%@&password=%@", username, password];
[request setHTTPBody:[post dataUsingEncoding:NSASCIIStringEncoding]];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//NSString *responseStr = [NSString stringWithUTF8String:[responseData bytes]];
//NSLog(@"Response : %@", responseStr);
NSString *json_string = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"JSON string : %@", json_string);
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *responseObj = [parser objectWithString:json_string error:nil];
NSArray *name = [responseObj objectForKey:@"first_name"];
NSLog(@"Name : %@", name);
}
The result from my NSLog for name is NULL
Where is the problem and how can I parse such a data so when it comes to lots of rows I can save it to the local FMDB database on iphone
------------------------------EDIT---------------------------------------------------------------
Actual problem was response JSON string from server included echo beginning of the string,json parser only parses between double quotes "", so all i just needed to trim echo from string and parse new string.
and bingo!
//trim in coming echo
NSString *newString1 = [json_string stringByReplacingOccurrencesOfString:@"correct username and password\n" withString:@""];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSArray *responseObj = [parser objectWithString:newString1 error:nil];
NSDictionary *dataDict = [responseObj objectAtIndex:0];
NSString *userID = [dataDict objectForKey:@"user_id"];
NSLog(@"user_id: %@", userID);
output : user_id : 7