Remove a field from an sObject object in Apex

This can be done using combination of serialize and deserialize tricks with SObject and Map. In short, you serialize your original sobject into JSON then deserialize it into untyped Map then modify the map's keys to add/remove any fields you want - or don't want - set. Then serialize the map back into JSON then deserialize it into your typed SObject.

// start with your original sobject
Account acct1 = new Account(
    name = 'Turkey',
    type = 'Gobble'
);
System.debug( 'Step 1. Account object: ' + acct1 );

// Step 2. Get map of the sobject fields
// In this variant, the populated fields map is read-only so pass it into another map to get an editable copy
Map<String, Object> acctMap1 = new Map<String, Object>( acct1.getPopulatedFieldsAsMap() );
System.debug( 'Step 2. Account populated fields map: ' + acctMap1 );

// Another way to do Step 2 is good ol' serialize/deserialize trick
Map<String, Object> acctMap2 = (Map<String, Object>) JSON.deserializeUntyped( JSON.serialize( acct1 ) );
System.debug( 'Another way to do Step 2. Account serialized as json then deserialized back into untyped map: ' + acctMap2 );

// Step 3. Remove any fields you don't want
acctMap1.remove( 'Type' );
System.debug( 'Step 3. Remove undesired field "Type" from map: ' + acctMap1 );

// Step 4. Convert the map into sobject using the good ol' serialize/deserialize trick
Account acct2 = (Account) JSON.deserialize( JSON.serialize( acctMap1 ), Account.class );
System.debug( 'Step 4. Account after serializing map of our desired fields into json then deserializing the json back into sobject: ' + acct2 );

Tags:

Apex