我使用NSURLSession
和NSURLSessionDataTask
发送帖子请求,然后获取响应并将其存储在NSString变量中,然后记录它。我的功能现在看起来像这样:
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) {
NSLog(@"Response:%@ %@\n", response, error);
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(@"Json = %@",text);
}
}];
[dataTask resume];
当我运行请求时,它会在调试终端中返回以下内容:
Json = {"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"}
我如何知道使用NSJSONSerialization
解析此问题?这甚至可以解析或我有一些格式化的PHP吗?这是我的第一个网络服务。
答案 0 :(得分:1)
NSJSONSerialization使用NSData而非NSString。
替换你的行...
NSString *text = [[NSString alloc] initWithData...
有这样的事情......
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
字典对象现在将代表JSON。
这取决于JSON是否正确,但是: - )
此外,此前已被问过数百次。
答案 1 :(得分:0)
NSMutableDictionary *json=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];