Skip to main content
Hi Friends

I have a custom object with 4 properties, First, Second, Third and Forth

Now I also have a Map<string, string> Values which has data as 

<First, 10>

<Second,20>

<Third, 30>

<Forth, 40>

Now I want a way to iterate over all the Keys in MAP and assign the value of corrosponding property of the object from value from MAP.

for(string keyValue : Map.GetKeys())

{

Object.Proeprty_Name = Map.Get(keyValue);

}

I can also do it other way by iterating over the properties of the object (by getting them using getMap()) and then see if the collection.ContainKey with that property Name.

Its kind of reflection in .net.

please guide on how to achieve it
1 answer
  1. Apr 15, 2020, 6:55 AM

    You can do it like blow assuming that map contains key values as string pair of object field name and value

    Map<String, Schema.SObjectType> descMap = Schema.getGlobalDescribe();

    Schema.SObjectType leadSchema = descMap.get(objectName);

    Map<String, Schema.SObjectField> fieldMap = leadSchema.getDescribe().fields.getMap();

    // objectRecord is the object of any custom or standard object

    // recordMap is the map of <String, String>

    for (String sfdcFieldName: recordMap.keySet()) {

    String fieldValue = recordMap.get(sfdcFieldName);

    Schema.DisplayType fieldDataType = fieldMap.get(sfdcFieldName).getDescribe().getType();

    if (String.isNotBlank(fieldValue)) { // this is just to make sure we are not setting blank. if you need to set blank then remove this check.

    if (String.valueOf(fieldDataType).equalsIgnoreCase('boolean')) {

    objectRecord.put(sfdcFieldName, Boolean.valueOf(fieldValue.toLowerCase()));

    }

    else if(String.valueOf(fieldDataType).equalsIgnoreCase('decimal') ||

    String.valueOf(fieldDataType).equalsIgnoreCase('currency') ||

    String.valueOf(fieldDataType).equalsIgnoreCase('double') ||

    String.valueOf(fieldDataType).equalsIgnoreCase('percent')) {

    objectRecord.put(sfdcFieldName, Decimal.valueOf(fieldValue.toLowerCase()));

    }

    else if(String.valueOf(fieldDataType).equalsIgnoreCase('date'))) {

    objectRecord.put(sfdcFieldName, Date.valueOf(fieldValue));

    }

    else if(String.valueOf(fieldDataType).equalsIgnoreCase('datetime'))) {

    objectRecord.put(sfdcFieldName, Datetime.valueOf(fieldValue));

    }

    else {

    objectRecord.put(sfdcFieldName, fieldValue);

    }

    }

    }

     
0/9000