Convert String to sObject in Salesforce Apex

While building a custom app in our Salesforce org, I added a feature where users can input the object’s name and other fields as strings. That dynamically creates and populates records based on user input or another source.

In this case, I had to create an account record using a string to specify the object type and then set some field values for this new record.

For this, I converted the input strings to the Salesforce Apex sObject data type, which converted the input strings to an account object record in the database.

In the steps below, I will explain how to convert a string to a sObject in Salesforce Apex using the Class method.

Convert String to sObject in Salesforce Apex

To convert a string to sObject in Salesforce Apex, navigate to the Salesforce developer console and follow the steps below.

  1. To create a new class in the developer console, select File > New > Class.
  1. Enter the Name for the new apex class and click the OK button.
  1. Enter the code below in the new Apex class and save it.
public class StringToSObject {
    public static void createDynamicRecord() {
        String str = 'Account';
        sObject obj = Schema.getGlobalDescribe().get(str).newSObject();
        
        obj.put('Name', 'Boston textiles');
        obj.put('Description', 'Primary account for the boston textiles');
        
        System.debug('sObject - ' + obj);
        insert obj;
    }
}
  • The sObject obj will create a new instance ( a record) based on the object type string. For example, if a string is ‘Account,’ a new account record will be created.
  • obj.put instances will populate the sObject fields with values. We can add multiple obj.put instances for multiple fields.
  • At last, insert obj will insert the record in the object database. (optional)
  1. If the above code has no problems (errors), execute the anonymous window with shortcut keys “Ctrl+E.”
  1. Enter the code below to execute the class method in the anonymous window. After that, click the Execute button.
ClassName.MethodName();
Convert string to Sobject in Salesforce apex
  1. In the Execution log window, select the checkbox to debug only, and there you will see the string converted to sObject with the fields of the sObject.
How to convert String to sObject in Salesforce apex

If you have used the insert obj, a record will be created in the object with the field values entered in the apex code.

Salesforce apex convert string to sObject

In this way, we can convert the string to sObject in Salesforce Apex by following the above steps.

Convert String List to sObject in Salesforce Apex

Using the Map function, we can also convert a list of strings to sObjects in Salesforce Apex. Now, follow the steps below to convert a list string to sObject in Salesforce Apex.

In this example, we will convert the string list to an account object record where we have a string containing values in a predefined order, such as [Name, Industry, Phone].

  1. Navigate to the developer console and select File > New > Apex Class to create an Apex class.
  1. Enter the new class’s name and click the OK button. After that, enter the below code in the new apex class and save it.
public class StringListToSObjectConverter {
    public static void convertAndInsertAccounts(List<List<String>> stringLists) {
        List<Account> accountsToInsert = new List<Account>();

        for (List<String> stringList : stringLists) {
            if (stringList.size() >= 3) {
                Account newAccount = new Account();
                
                newAccount.Name = stringList[0];
                newAccount.Industry = stringList[1];
                newAccount.Phone = stringList[2];
                
                accountsToInsert.add(newAccount);
            } else {
                System.debug('Skipping incomplete data: ' + stringList);
            }
        }

        if (!accountsToInsert.isEmpty()) {
            insert accountsToInsert;
        }
    }
}
  1. Now call the above class method in the Apex anonymous window using the code below.
List<List<String>> accountsData = new List<List<String>>();

accountsData.add(new List<String>{'Account 1', 'Technology', '1656423565'});
accountsData.add(new List<String>{'Account 2', 'Finance', '0987654321'});

// Call the method to convert and insert accounts
StringListToSObjectConverter.convertAndInsertAccounts(accountsData);

// too verify data conversion
System.debug('Accounts inserted from String List.');

In the above code, List<List<String>> accountsData converts a list of strings into Salesforce records. Each inner list contains values for fields like Name, Industry, and Phone in a specific order.

The method convertAndInsertAccounts goes through each inner list, checks if it has enough data, and assigns the values to an Account object.

If a list has missing fields, it is skipped with a debug message. The valid Account records are collected in a list and then inserted into Salesforce simultaneously.

Convert string list to sobject in Salesforce

This way, we can convert a String list to an Sobject in Salesforce Apex.

Conclusion

In this Salesforce tutorial, we learned how to convert a string and a string list to an sObject in Salesforce. By following the methods that we have discussed in the above example, you can convert the string to create single and multiple records dynamically using Schema.getGlobalDescribe() and the put() method.

You may also like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.