[SalesForce] How to store and JSON-serialize Map of Objects AND SObjects

This question is an extension to Write a generic JSON-serializable Parameters class without hitting “Apex Type unsupported in JSON: Object” where I learned how to serialize a Map to and from JSON.

My problem now is, that I also want to store SObjects as map values and always get a

System.TypeException: Invalid conversion from runtime type
MAP<String,ANY> to SOBJECT:Account

in the last line of this snippet:

Map<String, Object> parameters = new Map<String, Object>();
Account acme = new Account(Name = 'Acme Corp.');
insert acme;
parameters.put('SObject', acme);
String serialized = JSON.serialize(parameters);
parameters = (Map<String, Object>) JSON.deserializeUntyped(serialized);
Account restoredAcme = (Account) parameters.get('SObject');

Best Answer

Try adding this instead of your last line of code:

String jsonstr = (String)JSON.serialize(parameters.get('SObject'));
SObject restoredAcme = (Account)JSON.deserialize(jsonstr, Account.class);

The problem with what you're currently trying to do is that you're essentially trying to cast a Map to an Account - which as you've seen, you cannot do.

As a workaround, you can serialize the Map to String and then deserialize that String to an Account.