+ Start a Discussion
Sohan ShirodkarSohan Shirodkar 

How to escape a RestRequest body?

I have built a REST API POST service in apex. The way I am deserializing the recieved JSON request is as follows.
RestRequest request = RestContext.request;
String jsonBody = request.requestBody.toString();
jsonBody = String.escapeSingleQuotes(jsonBody);

MyDataClass data = (myDataClass )System.JSON.deserialize(jsonBody, MyDataClass.class);
Issue over here is that, if the JSON contains any key having value containing double-quotes(") or backslashes(\), the deserialization fails and I get an error response. When using POSTMAN, this is not a hurdle because POSTMAN immediately shows an error on the UI for such key-value pairs and doesn't allow us to make a request. But if we are making a call through code then this is problametic. 

I am currently using String.escapeSingleQuotes(), but not sure if this is of any use here.

Can I use replaceAll method as follows to escape all backslashes?:
If so can I use a similar way to escape all double-quotes?
Khan AnasKhan Anas (Salesforce Developers) 
Hi Sohan,

Greetings to you!

You can escape the slash with the help of replace function.
String response;

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

Map<String,String> kv = JSON.deserialize( str, Map<String,String>.class );

Please refer to below link which might help you further.


I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas