1

So far all I've been working with is receiving data from an restAPI using json in objective-c (using SBJson classes). I am now attempting to send post data but I have no experience with it. The raw body looks something like the following:

  //http://www.myapi.com/api/user=123
  "Username": "foo",
  "Title": null,
  "FirstName": "Nick",
  "MiddleInitial": null,
  "LastName": "Foos",
  "Suffix": null,
  "Gender": "M",
  "Survey": {
         "Height": "4'.1\"",
         "Weight": 100,
               }

What would be the best way this type of data?

2 Answers 2

1

Let's say you have the post data in a string, called myJSONString. (Getting from Objective-C collections to the json is straight-forward too. Looks like @Joel answered that).

// build the request
NSURL *url = [NSURL urlWithString:@"http://www.mywebservice.com/user"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";

// build the request body
NSData *postData = [myJSONString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
[request setValue:[NSString stringWithFormat:@"%d", [postData length]] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

// run the request
[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                           if (!error) {
                               // yay
                           } else {
                               // log the error
                           }
                       }];
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your response. I've got a question. I am also having to send a unique key as a customer header. How would I go about sending that as well?
Sure. [request setValue:@"value" forHTTPHeaderField:@"key"];
1

You want a dictionary with entries for each key above, then convert the dictionary to a JSON string. Note that the Survey key is a dictionary itself. Something like this.

NSMutableDictionary *dictJson= [NSMutableDictionary dictionary];
[dictJson setObject:@"foo" forKey:@"Username"];
...
[dictJson setObject:dictSurvey forKey:@"Survey"];

//convert the dictinary to a JSON string
NSError *error = nil;
SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init];
NSString *result = [jsonWriter stringWithObject:dictJson error:&error];
[jsonWriter release];

1 Comment

Thanks so much for the response. I had no idea how to approach the surveys dict. This will def work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.