[SalesForce] text Area field with newlines fails when sent via jSON call

I'm sending a field that is a Text Area (and therefore can have newlines and lots of empty space) into a a REST/JSON webservice. Works just fine when the field only contains a single line of text, but when there are newlines, they are passed as is into the JSON post body and look like this:

  {"CustomerNumber": "500269677904", "CustomerPhone":"8491163","CustomerName":"Kristján Jónsson","Lysing":"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, 


sunt in culpa qui officia deserunt mollit anim id est laborum","Text1":"null","Text2":"8491163"}

Here's the relevant code:

public static void CreateWorkorder(FieldServicesB2B__c wo,String ConsumerKey, String ConsumerSecret, String Endpoint) {

             String repairComm = wo.Comments__c.trim(); //This is the multi-line comment field                
            // String replaceAll = repairComm.trim(); 
             //repairComm.replaceAll('\r', '.');

            String content = '{"CustomerNumber": "500269677904","CustomerPhone":"'+
            wo.PhoneNumber__c+'","CustomerName":"'+ wo.Contact__r.Name+'","Lysing":"'+repairComm'","Text1":"'+
            wo.Contact__r.kennitala__c+'","Text2":"'+wo.PhoneNumber__c+'"}'  ;

           String endp = Endpoint;

I have also tried to use str.replaceAll('\n\r','') on the string variable but is stills sends the field contents with newlines and carriage returns.
What is the best method of dealing with this?

Best Answer

I think text area uses newline only ('\n'). So a replace like this:

repairComm.replaceAll('\n', '\\\\n')

will result in each newline character replaced with the two characters '\' and 'n' which is what is required in JSON. (The double escaping is required because of how regular expressions handle backslash.)

But it is safer to put this string through one of the Apex JSON methods as other escaping may also be needed (such as double quotes):

repairComm = JSON.serialize(repairComm);

But what you have in your text area is a mix of valid and invalid JSON so hard to cleanup without double escaping. If the JSON has fixed structure, it would be simpler to provide separate text fields for the multi-line input parts and combine them programmatically so the right escaping is applied where it is needed and not applied where it is not.

Related Topic