function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

How to handle special characters in json

i serialized a list ino JSON String.,


I am using HTTP Post to send that json to other end.,


I need to handle special characters in my JSON string,


Please help me.,


Hi nagsha


the apex json serializer escapes special characters.

e.g. If you have a " in your values, it will serialize \".




string jsonstring = "I have 10$ at myplace\r\ncity"


in the above string i need to remove $ ,\r\n.


string jsonstring = "I have 10 at myplacecity"


One quick thing you can do is just before you output the JSON is a simple string replace


String jsonWithSpecialChars = 'some text with a line break';




I already tried that folks.,


Here is what i am doing:


Map<> conMap = new Map<>();

String jsonstring = JSON.serializepretty(conMap.values());

String jsonModified = jsonstring.replaceall('\r\n','');


Http Object:




System debug('Output'+jsonmodified);----------------> here my string should replace \r\n with '',, but it's not working.,




String jsonModified = jsonstring.replaceall('\\r\\n','');
@Noam Thanks.. it works...  
I was having the same issue, but instead of using the replaceall function. I used the escapeJava function in apex (characters escaped include quotes and control characters, such as tab, backslash, and carriage return characters). For my case i was building a json string with the salesforce error encountered while inserting :

            insert ec;
            return '{"error": 0,"msg" : "' + system.label.VFP02MsgDemandeEnvoyee + '"}';
        catch(exception ex){
            return '{"error": 1,"msg" : "' + ex.getDmlMessage(0).escapeJava() + '"}';