I have large JSON response that I am trying to escape all instances of strings that are problematic for deserialization but am having some issues.

Using .replaceAll works but that throws a "Regex too complex" exception on large strings. Trying the same with .replace fixes the exception but now it doesn't handle the replace correctly for double quotes and throws an exception when deserializing.

Unexpected character ('t' (code 116)): was expecting comma to separate OBJECT entries

I tried to break it down and called replace 2 separate times but it's not working for double quotes.

HttpResponse response;

this.request.setEndpoint(ORG_BASE_URL + '/services/data/v' + this.version + '/ui-api' + this.normalizeResourcePath(uiApiResource));
response = this.client.send(this.request);

String responseString = response.getBody();

Map<String, String> REPLACEMENT_MAP = new Map<String, String>{
    '\n' => '\\\\n',        // new line character to escaped new line character
    '&quot;' => '\\\\"'     // html double-quote to escaped double-quote

for (String replace : REPLACEMENT_MAP.keySet()) {
   responseString = responseString.replace(replace, REPLACEMENT_MAP.get(replace));

return new Map<String, Object>{
    'body' => JSON.deserializeUntyped(responseString.unescapeHtml4()),
    'httpStatusCode' => response.getStatusCode(),
    '_version' => this.version
  • Why are you trying to do this? The response from the uiapi is already valid JSON. You might simply be misinterpreting the output depending how you're trying to output it.
    – sfdcfox
    Mar 27, 2020 at 5:47
  • It throws an exception when trying to deserialize the JSON response when a field's description or help text has line breaks or double quotes. Otherwise, I agree that there is no need to do any replacing.
    – 626
    Mar 27, 2020 at 6:19


You must log in to answer this question.

Browse other questions tagged .