获取方法JSON解析在IOS
我实现JSON解析如下:获取方法JSON解析在IOS
-(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 Method吗? Post &获取方法与有什么不同? *
是否有任何其他方式json解析?
您正在进行同步通信请求,导致应用程序变慢。您应该提出异步请求以保持您的应用程序响应。 它没有任何关于解析JSON数据的问题。
您正在使用主线程上执行的同步请求,所以如果您需要在后台使用异步加载。
POST方法: POST方法产生FORM集合,它被作为一个HTTP请求正文。表单中键入的所有值都将存储在FORM集合中。
GET方法: GET方法通过将信息附加到URL(带有问号)并将其存储为A查询字符串集合来发送信息。 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.
检查这个答案详细信息:what-is-the-difference-between-post-and-get
感谢您的回复.. – user2526811
@Nishant Tyagi你的回答清除了我的怀疑 – ChenSmile
我会建议在您的环境中使用AFNetworking
这将简化JSON
你得到的连接管理,后台排队的执行和解析背部形成服务器。
下面的代码示例将创建一个HTTP
客户端,其中base URL (<hostname>)
并从给定路径获得一个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 <path> from the server and parse the response to JSON
// this calls a GET method to <hostname>/<path>
[httpClient getPath:<your path> 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;
最后,你从那个特定的网址得到了回应,并且你想要它自己的方式。
[POST和GET有什么区别?](http://*.com/questions/3477333/what-is-the-difference-between-post-and-get) –