0

I implement the JSON Parsing as follow:

-(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"];

}

Using this code, it slow down the app. How can I parse the json in background? *Is this right for Post Method? what is the difference between Post & Get Method?*

Is there any other way to json parsing?

rmaddy
  • 298,130
  • 40
  • 468
  • 517
user2526811
  • 1,185
  • 4
  • 19
  • 50
  • possible duplicate of [What is the difference between POST and GET?](http://stackoverflow.com/questions/3477333/what-is-the-difference-between-post-and-get) – Parth Bhatt Jul 25 '13 at 10:30

5 Answers5

3

You are using synchronous request which is executed on Main thread so if you need to do it in background use asynchronous loading.

POST METHOD: The POST method generates a FORM collection, which is sent as a HTTP request body. All the values typed in the form will be stored in the FORM collection.

GET METHOD: The GET method sends information by appending it to the URL (with a question mark) and stored as A Querystring collection. The Querystring collection is passed to the server as name/value pair. The length of the URL should be less than 255 characters.

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.

Check this answer for more details : what-is-the-difference-between-post-and-get

Community
  • 1
  • 1
Nishant Tyagi
  • 9,615
  • 3
  • 36
  • 61
1

You are making synchronous communication request which slows down the application. You should make the asynchronous request to keep your app responsive. It is not having any concern with parsing JSON data.

Apurv
  • 16,578
  • 8
  • 47
  • 66
1

I would recommend using AFNetworking in your context which will simplify the connection management, background queue execution and parsing of the JSON you are getting back form the server.

The code example below will create an HTTP client with a base URL (<hostname>) and get a JSON payload from a given path. The network request runs in the background and runs a given block when completing

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
}];
Noor
  • 2,071
  • 17
  • 28
Eric Genet
  • 1,260
  • 1
  • 9
  • 19
0

Get: With the get method the value is send through the query string appended with the url. So you can see the the name, value, description on the addressbar when the page display in the browser.

Post: This method transfer the information through the complete form. You can not see the detail description on the addresss bar. When the page display.

Ashok Londhe
  • 1,462
  • 10
  • 28
Yogesh Kumar
  • 289
  • 4
  • 4
-1
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;

Finally u get the response from that specific url .and what ever u wanted to it do ur own way.

jean
  • 3,852
  • 4
  • 28
  • 45