0

I am using AFNetworking. The AFHTTPRequestOperationManager requestSerializer is set to use AFJSONRequestSerializer.

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager] manager.requestSerializer = [AFJSONRequestSerializer serializer];

HTTP Body with current setup: {"key" : "http:\/\/myURL.com\/}

Desired HTTP Body: {"key" : "http://myURL.com/}

How can I prevent / from being escaped with \?

Thomas R
  • 36
  • 4
  • cast the string to `NSString` and use `removingPercentEncoding`. – Ryan Apr 18 '18 at 20:57
  • 1
    https://stackoverflow.com/questions/19651009/how-to-prevent-nsjsonserialization-from-adding-extra-escapes-in-url ? – Larme Apr 18 '18 at 21:01
  • Thanks for pointing me in the right direction @Larme – Thomas R Apr 21 '18 at 15:45
  • There is a very, very high chance that you are confusing what _is_ in a string with what some tool displays. And if the body is supposed to be JSON, then both bodies are absolutely equivalent as JSON. If your server interprets them in different ways, then your server code is broken. – gnasher729 Apr 21 '18 at 16:25
  • @gnasher729 You are correct, the server code is broken and the reason for this question. Unfortunately it is not fixable at this time. – Thomas R Apr 25 '18 at 19:17

1 Answers1

0

In order to resolve this issue I subclassed AFJSONRequestSerializer and overrode requestBySerializingRequest:withParameters:error:

- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request withParameters:(nullable id)parameters error:(NSError *__autoreleasing  _Nullable * _Nullable)error {
    NSURLRequest *myRequest = [super requestBySerializingRequest:request withParameters:parameters error:error];

    NSData *jsonData = myRequest.HTTPBody;

    if (jsonData) {
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

        if (jsonString) {
            NSString *sanitizedString = [jsonString stringByReplacingOccurrencesOfString:@"\\/" withString:@"/" options: NSCaseInsensitiveSearch range: NSMakeRange(0, [jsonString length])];
            NSMutableURLRequest *mutableRequest = [myRequest mutableCopy];
            mutableRequest.HTTPBody = [sanitizedString dataUsingEncoding:NSUTF8StringEncoding];
            myRequest = mutableRequest;
        }
    }

    return myRequest;
}

This code was found here

Thomas R
  • 36
  • 4