ios中Json解析的Post&Get方法的区别

我实现JSON解析如下:

-(void)getallEvent { SBJSON *json = [SBJSON new]; json.humanReadable = YES; responseData = [[NSMutableData data] retain]; NSString *service = @"/GetAllVenue"; NSString *str; str = @"Calagary"; NSString *requestString = [NSString stringWithFormat:@"{\"CityName\":\"%@\"}",str]; //NSLog(@"request string:%@",requestString); // NSString *requestString = [NSString stringWithFormat:@"{\"GetAllEventsDetails\":\"%@\"}",service]; NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]]; NSString *fileLoc = [[NSBundle mainBundle] pathForResource:@"URLName" ofType:@"plist"]; NSDictionary *fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc]; NSString *urlLoc = [fileContents objectForKey:@"URL"]; urlLoc = [urlLoc stringByAppendingString:service]; //NSLog(@"URL : %@",urlLoc); NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlLoc]]; NSString *postLength = [NSString stringWithFormat:@"%d", [requestData length]]; [request setHTTPMethod: @"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody: requestData]; // self.connection = [NSURLConnection connectionWithRequest:request delegate:self]; NSError *respError = nil; NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ]; if (respError) { NSString *msg = [NSString stringWithFormat:@"Connection failed! Error - %@ %@", [respError localizedDescription], [[respError userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]]; UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Check your network connection" message:msg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alertView show]; [alertView release]; } else { NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding]; NSDictionary *results = [[responseString JSONValue] retain]; //NSLog(@" %@",results); NSString *extractUsers = [[results objectForKey:@"d"] retain]; NSDictionary *finalResult = [[extractUsers JSONValue] retain]; NSLog(@"Final Results : %@",finalResult); listOfEvents = [finalResult objectForKey:@"List of Event details of given Venue"]; 

}

使用此代码,它会降低应用程序的速度。 我如何解析背景中的json? * 这适用于Post方法吗? Post&Get方法有什么区别? *

有没有其他方法来json解析?

您正在使用在主线程上执行的同步请求,因此如果您需要在后台使用异步加载。

POST METHOD: POST方法生成一个FORM集合,它作为HTTP请求体发送。 表单中键入的所有值都将存储在FORM集合中。

获取方法: GET方法通过将信息附加到URL(带有问号)并将其存储为A Querystring集合来发送信息。 Querystring集合作为名称/值对传递给服务器。 URL的长度应小于255个字符。

 An HTTP GET is a request from the client to the server, asking for a resource. An HTTP POST is an upload of data (form information, image data, whatever) from the client to the server. 

请查看此答案以获取更多详细信息: post-and-get之间的区别是什么

您正在进行同步通信请求,这会降低应用程序的速度。 您应该发出异步请求以保持您的应用程序响应。 它对解析JSON数据没有任何顾虑。

我建议在您的上下文中使用AFNetworking ,这将简化连接管理,后台队列执行以及解析您从服务器返回的JSON

下面的代码示例将创建一个带有base URL ()HTTP客户端,并从给定路径获取JSON有效负载。 网络请求在后台运行,并在完成时运行给定的块

 httpClient = [[AFHTTPClient alloc] initWithBaseURL:url]; // set the type to JSON [httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]]; [httpClient setDefaultHeader:@"Accept" value:@"application/json"]; [httpClient setParameterEncoding:AFJSONParameterEncoding]; // Activate newtork indicator [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]; // Request the  from the server and parse the response to JSON // this calls a GET method to / [httpClient getPath: parameters:Nil success:^(AFHTTPRequestOperation *operation, id responseObject) { // responseObject is a JSON object here // } failure:^(AFHTTPRequestOperation *operation, NSError *error) { // handle error }]; 

获取:使用get方法,值通过附加url的查询字符串发送。 因此,当页面在浏览器中显示时,您可以在地址栏上看到名称,值,描述。

发布:此方法通过完整表单传输信息。 您无法在地址栏上看到详细说明。 页面显示时。

 NSString *myUrlString =[NSString stringWithFormat: @"your url]; NSString *postdata=[NSString stringWithFormat:@"emailId=%@&password=%@,username,password]; NSLog(@"%@",postdata); //create a NSURL object from the string data NSURL *myUrl = [NSURL URLWithString:myUrlString]; //create a mutable HTTP request NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:myUrl]; //sets the receiver's timeout interval, in seconds [urlRequest setTimeoutInterval:30.0f]; //sets the receiver's HTTP request method [urlRequest setHTTPMethod:@"POST"]; //sets the request body of the receiver to the specified data. [urlRequest setHTTPBody:[postdata dataUsingEncoding:NSUTF8StringEncoding]]; NSOperationQueue *queue = [[NSOperationQueue alloc] init]; //Loads the data for a URL request and executes a handler block on an //operation queue when the request completes or fails. [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { if ([data length] >0 && error == nil){ //process the JSON response //use the main queue so that we can interact with the screen dispatch_sync(dispatch_get_main_queue(), ^{ [self parseResponse:data]; }); } else if ([data length] == 0 && error == nil){ NSLog(@"Empty Response, not sure why?"); } else if (error != nil){ NSLog(@"Not again, what is the error = %@", error); } }]; } - (void) parseResponse:(NSData *) data { responseData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"JSON = %@", responseData); NSLog(@"Response ==> %@", responseData; 

最后你得到了那个特定url的回复。你想做的就是你自己的方式。