AFNetworking serializes forward slash making the JSON payload invalid

Deborshi Saha picture Deborshi Saha · Oct 9, 2015 · Viewed 7.7k times · Source

I am using AFNetworking 2.0.

In AFNetworking, AFHTTPRequestOperationManager object has an API:

(AFHTTPRequestOperation *)POST:(NSString *)URLString
                    parameters:(id)parameters
                       success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure

It accepts NSDictionary as params for the JSON Payload which we wish to 'POST' to the server. In my payload I have following key-value pair:

"buttonActionParam":"/catalog/special/international-calling"

Posting this payload server returns invalid JSON. Looking at the payload on the server side I realized that AFNetworking is actually sending:

"buttonActionParam":"\/catalog\/special\/international-calling".

I know that AFNetworking library uses NSJSONSerialization's class method -dataWithJSONObject:, which causes this. My question is:

Q. How to work around this issue?

Answer

Sulthan picture Sulthan · Oct 14, 2015

This is know problem. It actually behaves as designed (see https://stackoverflow.com/a/20448342/669586).

There are 3 possible solution:

  1. Make your server aware of the possibility that strings can be escaped. In general, this is the best solution.

  2. Use a different JSON encoder (e.g. SBJson) and encode the object to NSData instead of using AFNetworking default serializer.

  3. Encode using NSJSONSerialization and then convert the resulting data to a NSString (using NSUTF8StringEncoding), sanitize it and convert it back to NSData. Again, you have to do that before giving the object to AFNetworking.

The best way to implement 2 or 3 is setting a custom requestSerializer on the AFHTTPSessionManager instance. For example, see this answer for an example of implementing 3 (note it's in Swift).