Generate JSON String from Salesforce Records Update

Generate JSON String from Salesforce Records Update

JSON.serialize() method can be used to generate JSON String from Salesforce Records Update.

Sample Trigger to generate the JSON Payload:

trigger Accounttrigger on Account ( after update ) {
    
    List < Map < String, String > > payload = 
        new List < Map < String, String > >();
    
    for ( Account objAcc : trigger.new ) {
        
        Map < String, String > mapContent = 
            new Map < String, String >();
        
        Account oldAcc = trigger.oldMap.get(
            objAcc.Id 
        );
        
        if ( 
            objAcc.AccountNumber != oldAcc.AccountNumber 
        ) {
            
            mapContent.put(
                'AccountNumber', objAcc.AccountNumber
            );
            
        }
        
        if ( 
            objAcc.Description != oldAcc.Description 
        ) {
            
            mapContent.put(
                'Description', objAcc.Description
            );
            
        }
        
        if ( 
            mapContent.size() > 0 
        ) {
            
            mapContent.put( 
                'Id', objAcc.Id 
            );
            payload.add(
                mapContent 
            );
            
        }
        
    }
    
    if ( 
        payload.size() > 0 
    ) {
        
        System.debug(
            'payload is ' + 
            JSON.serialize(
                payload
            )
        );
        
    }
    
}

Sample Apex Code to update Account records to test:

List < Account > listAccounts = [
    SELECT Id, AccountNumber, Description
    FROM Account
    LIMIT 2
];

for (
	Account acc : listAccounts
) {
    
    acc.AccountNumber = 'Test';
    acc.Description = 'Sample';
    
}

update listAccounts;

Output:

Leave a Reply