Reputation: 1435
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?
Upvotes: 1
Views: 59
Reputation: 62686
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
}
}];
Upvotes: 1
Reputation: 16124
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];
Upvotes: 1