更改 AFJSONRequestSerializer 编码方式 JSON

change how AFJSONRequestSerializer encodes JSON

我正在使用 AFNetworking。 AFHTTPRequestOperationManager requestSerializer 设置为使用 AFJSONRequestSerializer。

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

当前设置的 HTTP 正文: {"key" : "http:\/\/myURL.com\/}

所需的 HTTP 正文: {"key" : "http://myURL.com/}

如何防止 /\ 转义?

为了解决这个问题,我将 AFJSONRequestSerializer 子类化并覆盖 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;
}

找到此代码here