3

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       test@test.co.uk

any ideas please ?

2

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', 'newemailaddress@example.com');

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
    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 Apr 26 at 15:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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