+ Start a Discussion
grahamHgrahamH 

Properly Escaping a BackSlash

Hi All,

I'm having an issue here with properly escaping a backslash in JSON.
I'm using System.JSON.deserialize() to parse some JSON and I have a value that is something like this

{"First Name" : "John \photographer"}

I realize the backslash needs to be escaped so I try changing the string to contain {"First Name" : "John \\photographer"} but when I try to deserialize this I get the following error

Unrecognized character escape 'p' (code 112) at [line:1, column:291]

To me this doesn't make any sense.  The first backslash should be escaping the second backslash and so there should not be any confusion with the "p" character.  

So far the only way I can get the deserialize method to run properly is by changing the string to be {"First Name" : "John \\\\photographer"}.  However as you would expect this yeilds the result "John \\photographer" as the value when it is displayed in the package which is not what I want.

Any help here?
Best Answer chosen by grahamH
Shruti SShruti S
You can escape the slash with the help of replace function offered by the String class. Here is how I did to achieve it -
String response;

response = response.replace( '\\', '\\' );

Map<String,String> kv = JSON.deserialize( str, Map<String,String>.class );
The response variable will have the JSON from the API. You can then replace the slash and finally deserialize it.

All Answers

Muhammad WasimMuhammad Wasim
Try this {"First Name" : "John \'Photographer"}
grahamHgrahamH

Hi Muhammad,  Thank you for replying.

When I try that, the value of "First Name" ends up becoming "John 'Photographer" which is not the value I'm expecting.

Shruti SShruti S
You can escape the slash with the help of replace function offered by the String class. Here is how I did to achieve it -
String response;

response = response.replace( '\\', '\\' );

Map<String,String> kv = JSON.deserialize( str, Map<String,String>.class );
The response variable will have the JSON from the API. You can then replace the slash and finally deserialize it.
This was selected as the best answer
Muhammad WasimMuhammad Wasim
Try this {"First Name" : "John \\/Photographer"}
Because backslash is an escape character so you'll probably get /photographer instead of backslash.
grahamHgrahamH
I have no idea why that works.  Because it doesn't actually look like you are replacing anything.  You are replacing '\\' with '\\' so really you shouldn't be changing the string.  

Somehow it works though.  So thank you!