[SalesForce] System.JSONException: Unexpected character (‘1’ (code 49)): was expecting comma to separate OBJECT entries

"sourceMessage": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><error code=\"VALIDATION_FAILED\">    <failure cause=\"INVALID_VALUE\" field=\"Status\" value=\"NotDefined\"/></error>"

Encountered the error mentioned in the Title when JSON.deserialize(jsonReponse, ApexClasss.class)

Even though the double quote is escaped in the value in front of version. Can someone help?

Best Answer

If the JSON text is in Apex code like this you will need two backslashes:

@IsTest
private class JsonTest {

    private static String s = '"sourceMessage": "<?xml version=\\"1.0\\" encoding=\\"UTF-8\\" standalone=\\"yes\\"?><error code=\\"VALIDATION_FAILED\\">    <failure cause=\\"INVALID_VALUE\\" field=\\"Status\\" value=\\"NotDefined\\"/></error>"';

    @IsTest
    static void test1() {
        JSON.deserializeUntyped(s);
    }

    @IsTest
    static void test2() {
        JSON.deserializeUntyped('{' + s + '}');
    }
}

as when the Apex is parsed \" maps to " (as the \ means ignore any special meaning of the following character) but you need to instead use \\" to map to \" on Apex parsing. Then the JSON parser at runtime sees an escaping backslash.

(I'm surprised test1 passes; sites like https://jsonformatter.curiousconcept.com don't consider that text to be valid JSON.)