Is it possible to convert an SObject to a Map?

The question is not very clear, but you could do something with the JSON.deserializeUntyped method as following:

testobject__c  tObj =  [SELECT boolfield__c,currencyfield__c,datetimefield__c,formulafield__c,Id,Name,numberfield__c,textfield__c,url_field__c FROM testobject__c limit 1];

Map<String, Object> m = (Map<String, Object>) JSON.deserializeUntyped(JSON.serialize(tObj));

system.debug(m.values());
system.debug(m.keyset());

I however somewhat assume that if you are going to to this in an interative fashion, or for bulky objects, this is not very performant, and you should take this into consideration. Be sure to know why you want to do this in your logic, and consider possible alternatives.

update: Salesforce released an apex native method to accomplish this. See dana's answer.


The sObject has a native function getPopulatedFieldsAsMap that converts from an sObject to a Map<String,Object>. This was released in Summer '16 which is probably why the other answers resort to using JSON serialization to accomplish this.

Account a = new Account();
a.name = 'TestMapAccount1';
insert a;
a = [select Id,Name from Account where id=:a.Id];
Map<String, Object> fieldsToValue = a.getPopulatedFieldsAsMap();

for (String fieldName : fieldsToValue.keySet()){
    System.debug('field name is ' + fieldName + ', value is ' +
        fieldsToValue.get(fieldName));
}

// Example debug statement output:
// DEBUG|field name is Id, value is 001R0000003EPPkIAO
// DEBUG|field name is Name, value is TestMapAccount1

It's doable if you de/serialize to JSON. The below may work but Sdry's untyped approach is superior:

Contact contactObject = new Contact(
  FirstName = 'Derp',
  LastName  = 'Herpinson'
);

String data = System.Json.serialize(contactObject);

Map<String,String> contactMap = (Map<String,String>)System.Json.deserialize(
  data.substringBefore('"attributes":{') + data.substringAfter('},'),
  Map<String,String>.class
);

System.debug(contactMap);
//{FirstName=Derp, LastName=Herpinson}

Tags:

Apex

Sobject