How to convert sObject to String in Apex?

To convert sObject to String in Apex, below is the simple code.

Example:

public Account acct = new Account(Name = 'Test Account');
String objType = String.valueOf(acct);
system.debug('objType is ' + objType);

Output:


Cheers!!!

4 comments:

  1. List abc =[select name from account Limit 50];
    String objType = String.valueOf(abc);
    System.debug(objType);

    it give me string of account id and account name , where I need only account names , how to solve this

    ReplyDelete
    Replies
    1. It gives Id when we used SOQL to get the account. You can use replace method with regular express to find id ='Id of the record' and replace it with blank.

      Delete