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
KruviKruvi 

Problem: Backslash is added to JSON before double quote

Hi

 

I need to save the original JSON I'm getting in the REST POST call-in to later send it in a callout.

To do that I have a text field on the object I create which holds the JSON string.

 

The problem is that a backslash is added before each double quote, and the system that gets this JSON when I callout can't process it.

 

Does anyone know why isn't the JSON saved in its original format and how can I work around this?

 

Many Thanks

 

 

 

soofsoof

1) Deserialize the original JSON into an Apex object

2) When creating the call-out JSON message, use JSONGenerator.writeObject() method to include the deserialized apex object as an object.

 

Does this make senes?  Can you try this?  Otherwise, JSONGenerator will always treat your 'original JSON message as a String, and always escape the quotes.

 

Thanks.

KruviKruvi

Thanks for the quick reply.

 

The original JSON has many fields I don't care about, I only need to save it in order to send it later in the callout to a system that does care about the content.

 

So if I Deserialize it I'm practically managing a lot of data I do not need or care about.

 

What can I do?

soofsoof

Makes sense!  I guess I'm not helping here, but it seems like the only 'clean' option you're left with is to parse the incoming message using JSONParser, and then using JSONGenerator re-write the message containing only those fields/values that you need.

 

Other than that, a crude method that I can think of is to do some kind of string manipulation and replace the escaped quotes w/ regular quotes.  Something like below:

String REPLACE_STRING = '~_~';
String initJsonStr = '{"str1": "this is string 1", "str2": "string 2", "str3": "string 3", "str4": "string 4", "int1": 550}';

JSONGenerator gen = JSON.createGenerator(false);
gen.writeStartObject();
gen.writeFieldName('initial-message');
gen.writeObject(initJsonStr.replace('"', REPLACE_STRING));
gen.writeEndObject();

String finalJsonStr = gen.getAsString().replace(REPLACE_STRING, '"');
System.assert(finalJsonStr.contains(initJsonStr));

 

 Thanks.

KruviKruvi

Thanks

 

I'm gone' try it out and let you know what I finally did...

KruviKruvi

I'm trying to go down the string replace path, so I wrote this:

 

String finalJsonStr = json.replace('\\"', '"'); 	 	
		
System.assert(finalJsonStr.contains('\\"'));	

 But the replacement is not happening, the final string still contains \"

 

Any suggestion?

soofsoof

I cannot think of why this wouldn't work... I tried your code and the quotes are being replaced for me, and the assertion fails.

Karen111Karen111
Did you find solution to this problem? As I am having similar issue.