我正在尝试学习如何解析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数据库
------------------------------ EDIT ------------- --------------------------------------------------
实际问题是来自服务器的响应JSON字符串包含字符串的echo开头,json解析器只在双引号“”之间解析,所以我只需要修剪字符串中的echo并解析新字符串。
和宾果!
//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
答案 0 :(得分:2)
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSArray *responseObj = [parser objectWithString:json_string error:nil];
NSDictionary *dataDict = [responseObj objectAtIndex:0];
NSString *name = [dataDict objectForKey:@"first_name"];
您是否打印过收到的数据?它显示从服务器接收数据?如果是,则尝试使用不同的编码。
答案 1 :(得分:0)
您可以在Mac App Store中使用Objectify(15美元)或JSON加速器(0.99美元)等工具为您自动生成数据模型,使模型像执行object.firstName一样简单。