我试图弄清楚如何从我的http响应中解析JSON。目前我正在使用NSURLSession任务发送帖子请求并获得响应和结果如下:
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSURL * url = [NSURL URLWithString:@"http://mysite.org/mobile_app/studentregister.php"];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
NSString * params = [NSString stringWithFormat:@"username=%@&displayname=%@&password=%@&passwordc=%@&email=%@&teachercode=%@", username, displayname, password, passwordc, email, teacherCode];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
NSError *serializeError = nil;
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&serializeError];
NSLog(@"Response:%@ %@\n", response, error);
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(@"Data = %@",text);
}
}];
现在,当我运行请求并记录以下响应时:
{"userCharLimit":"Your username must be between 5 and 25 characters in length"}{"displaynameCharLim":"Your displayname must be between 5 and 25 characters in length"}{"passLimit":"Your password must be between 8 and 50 characters in length"}{"emailInvalid":"Not a valid email address"}{"teacherCodeLength":"Your teacher code is not 5 to 12 characters"}
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
但我怎样才能解析:
{"userCharLimit":"Your username must be between 5 and 25 characters in length"}{"displaynameCharLim":"Your displayname must be between 5 and 25 characters in length"}{"passLimit":"Your password must be between 8 and 50 characters in length"}{"emailInvalid":"Not a valid email address"}{"teacherCodeLength":"Your teacher code is not 5 to 12 characters"} in ios?
答案 0 :(得分:2)
看一下NSJSONSerialization类。您将传递来自URL Connection的数据并返回基础对象的“对象图”。在你的情况下,看起来你会得到一本字典。
但更好的是使用AFNetworking。它可以在Github或CocoaPods上使用,并使所有这些东西变得非常容易。