Search code examples
iosobjective-cjsonnsjsonserialization

Why is API rejecting my JSON?


I can add an object to an API via JSON when I send the request using byte char[] however it doesn't work when I convert an NSDictionary to NSData and send that. What's the problem here ?

Here's when it works.

// Request

NSURL* URL = [NSURL URLWithString:@"SOME URL"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = @"POST";
request.timeoutInterval = 30.000000;

// Headers

[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

// Body

const char bytes[98] = "{\n\t\"user\" :\n\t{\n\t\t\"email\" : \"[email protected]\",\n\t\t\"username\" : \"example\",\n\t\t\"password\" : \"cryptx\"\n\t}\n}";
request.HTTPBody = [NSData dataWithBytes:bytes length:98];

// Connection

NSURLConnection* connection = [NSURLConnection connectionWithRequest:request delegate:nil];
[connection start];

This is when it doesn't work:

    - (void)addUser:(User *)user
{
    NSURL* URL = [NSURL URLWithString:@"API_URL"];
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
    request.HTTPMethod = @"POST";
    request.timeoutInterval = 30.000000;
    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
    NSData *data = [self createJSONWithUsername:@"X" andEmail:@"[email protected]" andPassword:@"pass"];
    [request setHTTPBody:data];
    NSLog(@"%@", [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding]);
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
    [connection start];
}

- (NSData *)createJSONWithUsername:(NSString *)username andEmail:(NSString *)email andPassword:(NSString *)password
{
    NSArray *objects = [NSArray arrayWithObjects:password, email, username, nil];
    NSArray *keys = [NSArray arrayWithObjects:@"password", @"email", @"username", nil];
    NSDictionary *userDataDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
    NSDictionary *userDictionary = [NSDictionary dictionaryWithObjectsAndKeys:userDataDictionary, @"user", nil];

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userDictionary options:NSJSONWritingPrettyPrinted error:nil];
    return jsonData;
}

The second one does not add the user while the second one does.

EDIT

JSON BEING SENT i.e. the jsonString variable

{
  "user" : {
    "email" : "[email protected]",
    "username" : "X",
    "password" : "pass"
  }
}

Solution

  • This is how I'd do it. It's pretty much exactly what I use in a few apps. I formatted around your provided code...

    - (void)addUser:(NSDictionary *)sentuserdetails {
      NSURL *url = [NSURL URLWithString:@"SOME URL"];
      NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
      request.HTTPMethod = @"POST";
      request.timeoutInterval = 30.000000;
      [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
      [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
      NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sentuserdetails      options:NSJSONWritingPrettyPrinted error:nil]; //don't set error to nil, handle the error
      [request setHTTPBody:jsonData];
      NSURLConnection *connection = [NSURLConnection connectionWithRequest:request           delegate:self];
      [connection start];
    }