HackaZach
HackaZach

Reputation: 409

iOS JSON serialization empty array serialized as nil instead of [ ]

I am attempting to send some JSON to a Rails backend. When serializing payload (NSDictionary), an empty array is encoding as nil instead of [ ] (empty array).

Is JSON encoding an empty NSArray as [] not supported on iOS?

I have tried changing the 'options' within dataWithJSONObject: with no success. Sending along @"[]" as a regular ol' NSString also does not work.

Here is the code:

NSData* jsonData = [NSJSONSerialization dataWithJSONObject:payload options:NSJSONReadingMutableLeaves error:&error];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:jsonData];
AFJSONRequestOperation *authRequest = [AFJSONRequestOperation JSONRequestOperationWithRequest:request  success:successBlock failure:failBlock];
[authRequest start];

Thanks for the help!

Upvotes: 1

Views: 956

Answers (1)

vdaubry
vdaubry

Reputation: 11439

I suspect the problem is coming from Rails and not from iOS, there is an issue related to a security hole in Rails since 3.2.11

https://github.com/rails/rails/issues/8832

https://github.com/rails/strong_parameters/issues/82

For example :

Sending an empty array in your body {"bookmarks":[]}

Gets serialized in Rails as : {"bookmarks"=>nil}

To be sure where the problem is coming from you should inspect the request using a proxy like Charles.

Upvotes: 1

Related Questions