Is it possible to convert an SOBject to a Map in a very few short lines of codes?
-
3Do you mean a list of SObject's? If so, Map<ID, SObject> myMap = new Map<ID, SObject>(mySObjectList); Will give you a map of SOBject's by Id.– Andrew FawcettFeb 21, 2013 at 12:09
-
1An Sobject has some of the behaviour of a Map<String,Object> - i.e. get/put methods. What are your reasons for wanting to convert an Sobject to a Map<String,Object> (I presume that's what you're after)?– Stephen WillcockFeb 21, 2013 at 12:16
3 Answers
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.
-
1
-
3Nice smart answer, though agree with "Be sure to know why..." Feb 21, 2013 at 13:33
-
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}