1

I am passing the trigger.old & trigger.New values from the trigger to batch class through JSON. In the class while deserializing the JSON i am getting only one list. How can i get two lists(old & New). Below is my code.. In Trigger:

String paramsJSONString; 
 paramsJSONString = Json.serializePretty(trigger.old);
 paramsJSONString = paramsJSONString + ',' +Json.serializePretty(trigger.new);

In Batch Class desereilizing:

list<CustomObject__c> listOfRecords = new list<CustomObject__c>();
 listOfRecords (list<CustomObject__c>)json.deserialize(paramsJSONString, list<CustomObject__c>.class);

By this way i am getting only one list. How to get old & new separate lists. Will this works for multiple records updations..?

0
4

I think your approach is somewhat questionable, but from an implementation standpoint, here are a few options available to you.

  1. Use Queueable, and you don't even need to serialize anything. You can instantiate the job with both lists.

For example:

public with sharing class MyCustomJob implements Queueable
{
    final List<SObject> oldRecords, newRecords;
    public MyCustomJob(List<SObject> oldRecords, List<SObject> newRecords)
    {
        this.oldRecords = oldRecords;
        this.newRecords = newRecords;
    }
    public void execute(QueueableContext context) { /* do stuff */ }
}
  1. Serialize a TriggerContext object for later deserialization.

The structure would simply look like:

public class TriggerContext
{
    final List<SObject> oldRecords, newRecords;
    public TriggerContext(List<SObject> oldRecords, List<SObject> newRecords)
    {
        this.oldRecords = oldRecords;
        this.newRecords = newRecords;
    }
}

Then you can freely serialize/deserialize as needed:

// in trigger
TriggerContext context = new TriggerContext(trigger.new, trigger.old);
String data = JSON.serialize(context);

// in batch
TriggerContext batchContext = (TriggerContext)JSON.deserialize(data, TriggerContext.class);
  1. Use a List<List<SObject>> for your serialization scheme.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.