Search code examples
iosobjective-cjsonencodingafnetworking

change how AFJSONRequestSerializer encodes JSON


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 \?


Solution

  • 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