Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to store a map of sObjects in a static resource. I want to be able to store default values for test setup methods. I was able to get it working with the following JSON in the static resource:

"Account" : "{\"attributes\":{\"type\":\"Account\"},\"BillingCity\" : \"testCity\"}",
"Opportunity" : "{\"attributes\":{\"type\":\"Opportunity\"},\"Name\" : \"testOpp\"}"

and here's the code:

String strJson = [SELECT body, name from StaticResource where Name =: myresource].body.toString();
mapJsonObjects = (Map<String, object>)JSON.deserializeUntyped(strJson);
Account objAccount = (Account) JSON.deserialize((String) mapJsonObjects.get('Account'),Sobject.Class);

The JSON I would actually like to have in the static resource is:


but there is no way to deserialize this into an sObject as far as I can tell.

share|improve this question
up vote 16 down vote accepted

You need to use the typed deserialize method as follows...

String jsondata = '{ "Account" : { "attributes":{"type":"Account"},"BillingCity" : "testCity"}, "Opportunity" : { "attributes":{"type":"Opportunity"},"Name" : "testOpp"}}';
Map<String, SObject> mapJsonObjects = (Map<String, SObject>)
    JSON.deserialize(jsondata, Map<String, SObject>.class);
Account objAccount = (Account) mapJsonObjects.get('Account');
System.debug('Account BillingCity is ' + objAccount.BillingCity);
Opportunity objOpportunity = (Opportunity) mapJsonObjects.get('Opportunity');
System.debug('Opportunity Name is ' + objOpportunity.Name);

The trick is using the .class property to get the class type of the typed Map.

Map<String, SObject>.class 

Results in

DEBUG|Account BillingCity is testCity

DEBUG|Opportunity Name is testOpp

share|improve this answer
Thanks so much! I was trying to deserialize into a map<string,sObject> for the longest time and eventually gave up after I kept getting weird errors. – Greg Grinberg Jan 22 '13 at 21:42
Your very welcome! :) – Andrew Fawcett Jan 22 '13 at 21:47
As an addendum to this idea, I found it necessary to use sObject.clone() when creating multiple records based on the default values in the Objects generated by from one JSON record otherwise I got "Before Insert or Upsert list must not have two identically equal elements" – AlwaysThinkin Oct 27 '14 at 18:06

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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