0

I'm creating a new REST API in salesforce and receiving the below JSON in Restrequest string

{"event_source":"","event_time":"2022-05-25 08:12:40.151","event_value":"{\"ad\":\"\",\"media_source\":\"restricted\"}"}

and when I try to deserialize in map I'm getting below error

DEBUG|Exception : Invalid conversion from runtime type String to Map

I'm using this conversation

Map<String, Object> params = (Map<String, Object>)System.JSON.deserializeUntyped(RestContext.request.requestBody.toString());
Map<String, Object> eventVal = (Map<String, Object>)params.get('event_value');

2 Answers 2

4

The decoded parameter is JSON, so you have to deserialize again:

Map<String, Object> params = (Map<String, Object>)System.JSON.deserializeUntyped(
  RestContext.request.requestBody.toString()
);
Map<String, Object> eventVal = (Map<String, Object>)JSON.deserializeUnTyped(
  (String)params.get('event_value')
);

If you can, I'd get that payload changed to something more "normal."

1
  • You nailed sfdcfox. I missed that the answer could be to parse a JSON inside of a JSON. May 26 at 15:28
3

That is because event_value is escaped inside of a string. Meaning it starts with quotes, and all quotes inside are escaped with a backslash:

{
  "event_source": "",
  "event_time": "2022-05-25 08:12:40.151",
  "event_value": "{\"ad\":\"\",\"media_source\":\"restricted\"}"
}

To parse differently, you need JSON changed in the source or modified by your code, but what seems to be expected is something around these lines:

{
  "event_source": "",
  "event_time": "2022-05-25 08:12:40.151",
  "event_value": {
    "ad": "",
    "media_source": "restricted"
  }
}
1
  • Thanks, your describe JSON working perfectly fine but when I try to String transformedJSON = jsonIpt.replaceALL('/',''); .....It;s still getting Exception...
    – whoisnilu
    May 26 at 8:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.