gpt4 book ai didi

ios - NSURLSession : Get Json from NSURLResponse

转载 作者:行者123 更新时间:2023-11-29 10:40:37 32 4
gpt4 key购买 nike

我正在尝试找出如何从我的 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?

最佳答案

看看 NSJSONSerialization 类。您会将来自 URL 连接的数据传递给它,并取回基础对象的“对象图”。在你的情况下,你会得到一本字典。

不过,更好的方法是使用 AFNetworking。它可以在 Github 或 CocoaPods 上找到,让所有这些事情变得非常简单。

关于ios - NSURLSession : Get Json from NSURLResponse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24718820/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com