0

I receive the following response from JSON.

{"Account":"{\"attributes\":{\"type\":\"Account\",\"url\":\"/services/data/v47.0/sobjects/Account/0014T000005aUbQQAU\"},\"FieldId__c\":\"0010I00002L0WNiQAN\",\"Id\":\"0014T000005aUbQQAU\"}"}

If I would want to convert this to a string,

String myJson = '{"Account":{"attributes":{"type":"Account","url":"/services/data/v47.0/sobjects/Account/0014T000005aUbQQAU"},"FieldId__c":"0010I00002L0WNiQAN","Id":"0014T000005aUbQQAU"}}';

How do I convert this so I can use it in the statement -

Map<String,Object> mapresp = (Map<String,Object>)JSON.deserializeuntyped(myJson);

1 Answer 1

4

This JSON is mangled: you have a single outer key, Account, whose value is not more JSON but a string value containing escaped JSON.

It would be best to fix this at the source of this JSON by correcting its logic. However, assuming this value is stored in a Map<String, Object> inputJSON, you can just deserialize the value of the Account property:

Map<String, Object> response = (Map<String, Object>)JSON.deserializeUntyped(
    (String)inputJSON.get('Account')
);
4
  • this is the code that is sending this response. Is being received as Map<String,String> Map<String, String> tosend = new Map<String,String>(); for(Account objAccount :[SELECT FieldId__c,Id FROM Account WHERE Id=:acc.Id]){ tosend.put('Account',JSON.serialize(objAccount)); } In return, I get the response as what is stated above. If I do convert the response to a string, then I should be able to navigate to FieldId__c. But how do I convert the response to a string?
    – Priya
    Dec 2, 2019 at 9:29
  • tosend.put('Account',JSON.serialize(objAccount));: this is the source of your issue. You should not be serializing the material here; instead, allow the system to perform the required JSON serialization from the data structure you prepare.
    – David Reed
    Dec 2, 2019 at 16:37
  • Hi David, I don't think I understand that. So, I am trying to send this information to Org2 from Org1 and the return type is map<string,string>. The response body is what I got in Org2. If I do not serialize the request to be sent, how else will it be sent?
    – Priya
    Dec 3, 2019 at 15:42
  • You could potentially change the return type to Map<String, Object>, or use a concrete Apex class that the system can serialize for you. There's lots of examples on SFSE.
    – David Reed
    Dec 3, 2019 at 21:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .