[SalesForce] JSON Exception unexpected character

I am doing a callout to a google script which takes in address and returns back geographic information (lat, lng etc) in the form of JSON string.

The problem is that in the returned JSON string " is replaced by \". So the JSON response is something like :

{\"results\":[{\"address_components\":[{\"long_name\":\"435\",\"types\":[\"street_number\"],\"short_name\":\"435\"},{\"long_name\":\"West Huron Street\",\"types\":[\"route\"],\"short_name\":\"W Huron St\"},{\"long_name\":\"Old West Side\",\"types\":[\"neighborhood\",\"political\"],\"short_name\":\"Old West Side\"},{\"long_name\":\"Ann Arbor\",\"types\":[\"locality\",\"political\"],\"short_name\":\"Ann Arbor\"},{\"long_name\":\"Washtenaw County\",\"types\":[\"administrative_area_level_2\",\"political\"],\"short_name\":\"Washtenaw County\"},{\"long_name\":\"Michigan\",\"types\":[\"administrative_area_level_1\",\"political\"],\"short_name\":\"MI\"},{\"long_name\":\"United States\",\"types\":[\"country\",\"political\"],\"short_name\":\"US\"},{\"long_name\":\"48103\",\"types\":[\"postal_code\"],\"short_name\":\"48103\"}],\"formatted_address\":\"435 West Huron Street, Ann Arbor, MI 48103, USA\",\"types\":[\"street_address\"],\"geometry\":{\"bounds\":{\"southwest\":{\"lng\":-83.75289409999999,\"lat\":42.28154259999999},\"northeast\":{\"lng\":-83.7528932,\"lat\":42.2815563}},\"viewport\":{\"southwest\":{\"lng\":-83.75424263029151,\"lat\":42.2802004697085},\"northeast\":{\"lng\":-83.75154466970851,\"lat\":42.2828984302915}},\"location_type\":\"RANGE_INTERPOLATED\",\"location\":{\"lng\":-83.75289409999999,\"lat\":42.28154259999999}}}],\"status\":\"OK\"}

This gives me an error- System.JSONException: Unexpected character ('\' (code 92)): was expecting double-quote to start field name at [line:1, column:3]

As you can see the " are replaced by \".

To counter this I am doing a replaceAll('\"', '"') but this is not helping. The final string still contains \"

I performed the same replace in my anonymous execute and it worked but it does not work in the apex class.

There already exists a similar question to this one on Stackoverflow but it did not help me much.

Any idea on why the replaceAll() is not working? Or any other way I can remove the \ from the response?

Thanks for the help.

Best Answer

You can use the built in String.unescapeEcmaScript() method to remove the escape characters in that JSON string. This will also take care of any other escaped characters that may be in your string value.

// shortened your string value
string original = '{\"results\":[{\"address_components\":[{\"long_name\":\"435\",\"types\":[\"street_number\"]';

String s = original.unescapeEcmaScript();
system.debug(s);

DEBUG|{"results":[{"address_components":[{"long_name":"435","types":["street_number"]

Related Topic