0

I have succeeded in making a post using a HTTP Client by setting the content type as application/json and this json code:

{
    "order": {
        "name": "Tia Carter",
        "location": "Corams",
        "phone_number": "707",
        "food": "Bobcat Burger"
    }
}

The code works perfect and the order is registered in the database. I am trying to work this into my iOS app but keep getting syntax errors regarding the colons in the json. This is the objective-c code:

NSURL *nsURL = [[NSURL alloc] initWithString:@"http://0.0.0.0:3000/orders.json"];
NSMutableURLRequest *nsMutableURLRequest = [[NSMutableURLRequest alloc] initWithURL:nsURL];

// Set the request's content type to application/x-www-form-urlencoded
[nsMutableURLRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

// Set HTTP method to POST
[nsMutableURLRequest setHTTPMethod:@"POST"];

// Set up the parameters to send.
NSString *paramDataString = [NSString stringWithFormat:@
                             "{ "order":  {"%@:" ="%@","%@:"="%@","%@:"="%@","%@:"="%@"}}", @"name", _name.text, @"location", _location.text, @"phone_number", _phoneNumber.text, @"food", _order.text];

// Encode the parameters to default for NSMutableURLRequest.
NSData *paramData = [paramDataString dataUsingEncoding:NSUTF8StringEncoding];

// Set the NSMutableURLRequest body data.
[nsMutableURLRequest setHTTPBody: paramData];

// Create NSURLConnection and start the request.
NSURLConnection *nsUrlConnection=[[NSURLConnection alloc]initWithRequest:nsMutableURLRequest delegate:self];

I'd appreciate any ideas or guidance. Thanks.

Victor Ronin
  • 22,758
  • 18
  • 92
  • 184
Matt Perejda
  • 509
  • 5
  • 14

1 Answers1

0

I believe you have two problems:

  • You didn't escape quotas (put \ before all of them)
  • You don't need to put text "name", "location" and etc in parameters (it's not a problem per se, just a style thing)

Also, I would recommend to work with NSDictionary and convert it to JSON when you need to (it will save you a lot of nerves for unescaped quotas, missing bracket and so on).

Look this question how to convert NSDictionary to JSON:

Generate JSON string from NSDictionary in iOS

Community
  • 1
  • 1
Victor Ronin
  • 22,758
  • 18
  • 92
  • 184