Tuesday, 22 December 2015

JSON parsing using POST method in iOS.

In this post ,i will tell you about JSON parsing and how to post data to server using NSUrlConnection .

JSON parsing is very useful and is used in almost every application to send or retrieve data from a online server .

JSON stands for JAVA SCRIPT OBJECT NOTATION. It is always shown in app in key - value pair form i.e. Dictionary

eg :- {"name" : "Saurabh", "Country" : "India"}


Here name and Country are keys 
Saurabh and India are values.


To know more about Dictionaries ,go to my previous post about NSDictionary  .

Now , lets move to the example to know more about JSON parsing in iOS.

Step 1 : Create a dictionary which you want to post to the web service

    NSMutableDictionary *postData = [[NSMutableDictionary alloc]init];

    [postData setObject:uid forKey:@"id"];


Step 2 : Convert dictionary into NSData using NSJSONSerialization . 

    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:postData options:kNilOptions error:nil];


Step 3 : Convert the NSData into NSString using NSUTF8StringEncoding.

    NSString *jsonInputString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    NSString *post = [[NSString alloc]initWithFormat:@"%@",jsonInputString];
  

Step 4 : Add your Url where you want to post data and convert it into NSData form.

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"YOUR URL "]];

    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];


Step 5 : Make NSUrlMutableRequest and add its properties .

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120.0];
    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
    
    NSError *error;
    NSURLResponse *response;

Step 6 : Make a NSURL connection to make connection with server.

    NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    
    NSDictionary *jsonDict;

Step 7 : Convert the data which is received from server into the JSON format using JSON serialization.

    if (responseData != nil)
    {
        jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
        NSLog(@"jsonDoct == %@",jsonDict);
    }
    else
    {
        NSLog(@"RESONPSE IS NULL");
    }

Step 8 : Error handling
    
    if (error)
        {
            NSLog(@"error %@",error.description);
        }

Thats all about JSON parsing using POST variable.

Thank you. :)




No comments:

Post a Comment