I have an api response which is been parsed to a map using JSON.deserializeUntyped function. In the response , i have a key value pair as: '{"primaryuser": "test\\test"}'

When i try to fetch it from the map , i need the backslash character. But below string is obtained :


Now since backslash character is escaped , when i try to find backslash character , it doesn't showup.

Please find below code for reproducing this issue :

String str = '{"primaryuser": "test\\test"}'; 
Map<String,Object> maps= (Map<String,Object>)JSON.deserializeUntyped(str);
System.debug('str '+str);
System.debug('value '+maps.get('primaryuser'));

Below is the debug log which i'am getting :

18:42:44.27 (29338484)|USER_DEBUG|[4]|DEBUG|value test  est

On deserialization, you are successfully escaping the backslash, which makes the deserialized string 'test\test'

\t is the escape sequence for a tab, which is exactly what you're seeing in your example output ('test\test' ==> 'test est').

To solve this problem, you need more backslashes (a total of 4, to be precise).

'test\\\\test' is deserialized to 'test\\test', which when printed will appear as 'test\test'.

Alternatively, replacing backslashes for a forward slash would also work. Using your example code:

String str = '{"primaryuser": "test\\test"}';
str = str.replace('\\', '\\\\'); //str.replace('\\', '/'); // replacing with a forward slash would also work
Map<String,Object> maps= (Map<String,Object>)JSON.deserializeUntyped(str);
System.debug('str '+str);
System.debug('value '+maps.get('primaryuser'));
  • thank you for the answer, is there any other way to get around this issue? – Rohit C Oct 10 '19 at 15:27

This will fix the issue, but if you are pulling in the value from elsewhere you may need to do a quick replace to get to this

String str = '{"primaryuser": "test\\/test"}'; 
  • str is actually coming from rest API. – Rohit C Oct 10 '19 at 14:29
  • parse and replace the return string before deserializing it – curtisk Oct 10 '19 at 14:40
  • Thank you for the suggestion, but that would be my last option. – Rohit C Oct 10 '19 at 15:27
  • Then get the person providing the feed to change it on their side – curtisk Oct 10 '19 at 15:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.