Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting JSON in Objective-C

I've got a fairly easy question today. I have an app that needs to send a simple JSON array to a remote server in the form of 2D GPS coordinates. The app will use the CoreLocation framework in order to generate these coordinates. For now, I want to hard code some sample coordinates to get the JSON right. However, I cannot seem to form the JSON correctly within the ObjC code.

Here is the code:

NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:myserver/handler/index"]];
[request setHTTPMethod:@"POST"];
NSString *jsonString = @"{"
@"  \"geo\": {"
@"    \"lat\": \"37.78\","
@"    \"lon\": \"-122.40";
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[request setHTTPBody:jsonData];
(void)[[NSURLConnection alloc] initWithRequest:request delegate:self];

Here is what the server is expecting (but not receiving):

{
"geo": {
    "lat": "37.78",
    "lon": "-122.40"
}

I'm sure it's a simple JSON formatting issue or otherwise numskull move on my part.

Any help is always appreciated!

like image 636
ebeniezer Avatar asked Jul 12 '26 10:07

ebeniezer


1 Answers

You are doing this the hard way. Create an NSDictionary then convert that to the desired JSON data:

NSDictionary *dictionary = @{ @"geo" : @{ @"lat" : @"37.78", @"lon" : @"-122.40" } };
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
if (jsonData) {
    // process the data
} else {
    NSLog(@"Unable to serialize the data %@: %@", dictionary, error);
}

No need for the string at all.

Edit: If your real data is an array of objects then create an array of dictionaries or whatever structure you need. The rest is the same.

like image 98
rmaddy Avatar answered Jul 15 '26 03:07

rmaddy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!