Fetch field API name and field value in SOQL

apexdynamic-soqlsoql

I have a requirement where I have to get data using dynamic SOQL on the go. I am successfully able to form the dynamic query with fields that are provided during run time and get data as well.

Once the data is fetched I need to be able to map the field API name with the value from the query result. How can I do this dynamically, since I don't know what fields are going to be queried?

        objectFieldList = [Select Mapping_Field_API_Name__c from customObject__c]; //Mapping_Field_API_Name__c contains values like Opportunity.Email
        for(customObject__c co : objectFieldList ){
            List<String> splitData = co.Mapping_Field_API_Name__c.split('\\.');
            System.debug('splitData :'+ splitData);
            if(splitData[0] == 'Opportunity'){
                oppFields.add(splitData[1]);
            }     
        }
        String queryFieldsFinal = '';
        for(String s : oppFields){
            queryFieldsFinal += s+','; 
        } 
        queryFieldsFinal = queryFieldsFinal.substring(0, queryFieldsFinal.length()-1);
        String queryOpp = 'SELECT '+queryFieldsFinal+' FROM Opportunity WHERE Id = :opportunityId';
        oppList = Database.query(queryOpp);

From the code I have shared, you can see I am able to get the data but now I want to have a map where I can store it in this format fieldAPIValueMap(API Name, field-value); or alternatively, something similar so that I can know the field that was queried and value that was fetched.

Best Answer

As you already have list of fields you can use that to create map

Map<String, Object> mapToStoreField = new Map<String, String>();
oppList = Database.query(queryOpp)
for(String s : oppFields){
   mapToStoreField.put(s,oppList[0].get(s)); //Using get you will get value dynamically.
//Also as there can only be 1 record so not iterating over list and simply taking first element.
}
Related Topic