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?
This is know problem. It actually behaves as designed (see https://stackoverflow.com/a/20448342/669586).
There are 3 possible solution:
Make your server aware of the possibility that strings can be escaped. In general, this is the best solution.
Use a different JSON encoder (e.g. SBJson) and encode the object to NSData
instead of using AFNetworking default serializer.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With