+ Start a Discussion
NagShaNagSha 

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.,

Noam.dganiNoam.dgani

Hi nagsha

 

the apex json serializer escapes special characters.

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

 

 

NagShaNagSha

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"

Chris42Chris42

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';

 

 jsonWithSpecialChars.replaceall('\r\n','');    

NagShaNagSha

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:

 

setbody(jsonModified)

 

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

 

 

Noam.dganiNoam.dgani
Try


String jsonModified = jsonstring.replaceall('\\r\\n','');
adityaMorganadityaMorgan
@Noam Thanks.. it works...  
vanessenvanessen
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 :

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