Post JSON to a webservice

August 28, 2008    JSON Programming Snippets

Make sure you have JSON Framework installed first.

This is a continuation of UIImageView in a custom cell

Here is a simple little code snippet on how to post some JSON to a webservice.

NSString *requestString = [NSString stringWithFormat:@"json=%@", [loginDict JSONFragment], nil];
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http://domain.com/api/login/"]];
[request setHTTPMethod: @"POST"];
[request setHTTPBody: requestData];

NSData *returnData = [ NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];

// decoding the json
NSDictionary *loginArray = [NSDictionary alloc];
loginArray = [returnString JSONValue];

So below is what each line does.

  • First we format the request string. What I am doing there is taking a whole dictionary and making it a JSON object. I then assign that to the json variable to post in. So in PHP land that would come in as $_POST[‘json’]  and I could do like json_decode($_POST[‘json’]) and turn it into an array I can work with in PHP
  • The next line turns the request into a data object so we know how big the string is.
  • Now we setup the URL to post the request to
  • We are setting the method to a post in html land it is like
  • Now are are setting up the body of the post with our data
  • We now make the connection to the server and then get a data string back
  • We decode the data stream into a NSString object
  • Since you send in JSON I expect you get JSON back so we take the contents of the NSString and turn it into a NSDictionary

Pretty simple. That is all there is to it.



comments powered by Disqus