我正在尝试学习如何解析 JSON 数据,以便处理大型数据库。我编写了登录网站的代码。
我从成功的登录请求中获得了以下 JSON 数据:
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"}]
我使用以下代码进行解析,但它不解析它
-(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);
}
我NSLog
的名字的结果是NULL
问题出在哪里,如何解析这样的数据,所以当涉及到很多行时,我可以将其保存到 iPhone 上的本地 FMDB 数据库中
- - - - - - - - - - - - - - - 编辑 - - - - - - - - - - ------------------------------------------
实际问题是来自服务器的响应 JSON 字符串包含字符串的回显开头,json 解析器仅在双引号“”之间解析,所以我只需要从字符串中修剪回显并解析新字符串。
和宾果游戏!
//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);
输出:user_id:7