4

I am trying to create a map from a result of a SOQL query, this map contains the name of the fields as keys and the values of the query as values for example:

List accounts = [SELECT Name, Email FROM Account];

and the map Map has this structure:

key         value
name        123 
email       [email protected]

any ideas please ?

1
  • 1
    Why do you need it to be a map?
    – Adrian Larson
    Commented Mar 7, 2016 at 15:33

2 Answers 2

3

An SObject record has a very map-like structure by default.

Account record = [SELECT Name, Email FROM Account LIMIT 1];
system.debug(record.get('Name');
system.debug(record.get('Email');

It even supports put:

record.put('Email', '[email protected]');

However, if you absolutely must have a map for some reason, you can use serialization (a CPU intensive process) as follows:

String representation = JSON.serialize(record);
Map<String, Object> dataMap = (Map<String, Object>)JSON.deserializeUntyped(representation);
dataMap.remove('attributes');
2

SObject.getPopulatedFieldsAsMap() does the job for you. From Summer '16 this feature is available to convert SObject class to map.

https://releasenotes.docs.salesforce.com/en-us/summer16/release-notes/rn_apex_sobject_getmap.htm

1
  • 2
    I wouldn't necessarily say that it converts the SObject into a Map<String, Object>, as the original SObject remains intact. It certainly takes a given SObject and generates/returns a Map<String, Object> though. I might just be nit-picking.
    – Derek F
    Commented Apr 26, 2019 at 15:43

You must log in to answer this question.

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