Can you send json from VisualForce to Apex and have it be valid?

I have this JSON object that I’ve gotten from the front end. I want to send it to Apex and finally send it to my external API.

Visualforce:

 ct_4_sf.RecordingTest.saveVideo(
     data, //{key:'value',key2:'value2'}
     function(response){

     }
 );

If I attempt to just send it from visualforce to this apex function:

Apex:

@RemoteAction
global static String saveVideo(String data) {
    System.debug(LoggingLevel.INFO,'saving ' + data);
    return Connector.saveVideo(JSON.serialize(data));
}

The saving log will print something like this:

{key=value, key2=value2}

All the colons are now replaced with equal signs, which is invalid JSON.

How can I either turn this back into valid json, or send valid json in a way that it doesn’t corrupt on the other side?

Answer

Convert the JSON into string before sending to controller using JSON.stringify(). Please check below link,

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Also if there is no other operation that needs to be done in controller before sending to external system. Try to do it in page only using javascript/jQuery AJAX

http://api.jquery.com/jquery.ajax/

Attribution
Source : Link , Question Author : Community , Answer Author : Victor

Leave a Comment