Post JSON to a webservice
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 <form method=”POST”>
- 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
7 Responses to “Post JSON to a webservice”
Leave a Reply

can you some example of how to connect to .NET web-services using SOAP?
@Amit
The quick answer to that is no.
1) I am not a MS person. I haven’t touched windows in ages cept for my laptop I keep for my future wife to use
2) I have always hated SOAP with a passion.
Sorry!
[...] This is a continuation of Post JSON to a webservice [...]
Great tutorial!
There is one small change I had to do. The [loginDict JSONFragment] isn’t url encoded, which causes problems if any of the values in the dictionary contains an ampersand (&). Otherwise, no problems!
Thanks your code, but I try hard to get Json from iphone in PHP. But it didn’t work, could you please have examples about this.
Any chance you can show how to post a file via JSON?
Thanks!
Hello sir.
i am developing an iphone application for a youtube like website.
I want to talk with website database from my iphone application.
want to insert user comment,rating, and other data to website database. Will you guide me please..
i am very fresh to iphone development.