Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backslashes "\" added in JSON string for web service in swift

In my project I need to send JSON object in web service API call. I have converted JSON from array.

do {

       let theJSONData = try NSJSONSerialization.dataWithJSONObject(
                        param ,
                        options: NSJSONWritingOptions(rawValue: 0))

       var theJSONText : String = String(data: theJSONData,
                        encoding: NSASCIIStringEncoding)!

       print(theJSONText)

       theJSONText = theJSONText.stringByReplacingOccurrencesOfString("\\", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)

       print(theJSONText)

       let newParam = ["ESignData":theJSONText]


} catch let error as NSError {
                    print(error)
                }

it print string correctly as

{"EntNum":"47","JobNo":"1737753","ClientID":"100","HospNo":"1","QAReason":"","DoctorNo":"1694","Action":"Sign"}
{"EntNum":"47","JobNo":"1737753","ClientID":"100","HospNo":"1","QAReason":"","DoctorNo":"1694","Action":"Sign"}

Now When I try to send this newParam dictionary in API call, it contains "\" in string parameters of JSON string.

WebService.PostURL(mainLink, methodname: ESIGNTHISDOC, param: newParam, userName: AUTH_USERNAME, password: AUTH_PWD, CompletionHandler: { (success, response) in
})

And in that web service method I have print param.

Param =  {
    ESignData = "{\"EntNum\":\"47\",\"JobNo\":\"1737753\",\"ClientID\":\"100\",\"HospNo\":\"1\",\"QAReason\":\"\",\"DoctorNo\":\"1694\",\"Action\":\"Sign\"}";
}

Now in this I know it is obvious in iOS because of " in string. Now the problem is that there are lots of APIs working in android app, and the API developer doesn't want to update his code according to us.

I know this problem happens because of adding JSON string in dictionary as parameter. But I have not proper justification for that so if any proof will be also helpful for me to convince him.

Any solution to convert the JSON string without backslash in iOS? I need to fix from my side if possible. Any help will be appreciate.

EDIT :

On server side it needs like

ESignData = {"EntNum":"47","JobNo":"1737753","ClientID":"100","HospNo":"1","QAReason":"","DoctorNo":"1694","Action":"Sign"}

If I pass this as parameter in POSTMAN than it gives success message. But not with our object with "\" in it.

EDIT 2:

Now printing the newParam dictionary:

print(newParam)
print("-------------------------")
print(newParam["ESignData"])

And logs :

["ESignData": "{\"EntNum\":\"47\",\"JobNo\":\"1737754\",\"ClientID\":\"100\",\"HospNo\":\"1\",\"QAReason\":\"\",\"DoctorNo\":\"1694\",\"Action\":\"Sign\"}"]
-------------------------
Optional("{\"EntNum\":\"47\",\"JobNo\":\"1737754\",\"ClientID\":\"100\",\"HospNo\":\"1\",\"QAReason\":\"\",\"DoctorNo\":\"1694\",\"Action\":\"Sign\"}")

And by debug :

Printing description of newParam:
▿ 1 elements
  ▿ [0] : 2 elements
    - .0 : "ESignData"
    - .1 : "{\"EntNum\":\"47\",\"JobNo\":\"1737754\",\"ClientID\":\"100\",\"HospNo\":\"1\",\"QAReason\":\"\",\"DoctorNo\":\"1694\",\"Action\":\"Sign\"}"

So it shows that it is in our dictionary. All the " are joined by \.

like image 626
Max Avatar asked Nov 09 '22 12:11

Max


1 Answers

I ran into this exact issue today. For me it appears that the default encoding for any NSURLRequest is a string. So, somewhere between my creating the dictionary request and the server parsing it, the backslashes would appear and the server had problems with my payload.

I solved the issue by explicitly stating that my payload was JSON by setting the content type header.

    [authRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

Now when I create JSON data from a dictionary, the backslashes don't appear and the server is able to parse everything correctly.

Code snippet below for completeness:

   NSMutableURLRequest *authRequest = [[[NSURLRequest alloc] initWithURL:authURL] mutableCopy];
[authRequest setHTTPMethod:@"POST"];
NSURLSession *session = [NSURLSession sharedSession];

[authRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

NSDictionary *bodyDictionary = @{@"User_Name": user, @"Password_Hash": password};

if ([NSJSONSerialization isValidJSONObject:bodyDictionary]) {
    NSError *error;
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:bodyDictionary options:0 error:&error];
    if (!error) {
        [authRequest setHTTPBody:bodyData];
    } else {
        NSLog(@"Unable to convert to JSON DATA %@", error.localizedDescription);
    }
}
like image 120
Walter Avatar answered Nov 14 '22 23:11

Walter