0

I am trying to pass a list Account records to a future method. Since future can only take primitives, I am planning to serialize and deserialize the Sobject. I tried below:

List<Account> acList;// I get a list of account from some other method.
String str = JSON.serialize(acList);


@future
public static void createAccount(String inp){
List<Account> acc = (List<Account>) JSON.deserialize(inp); // this is not correct. I am trying to figure out a way where I could use something like this. 
insert acc;
}

Is there a way I could achieve this?

  • 1
    Is there a reason why you need to use @future here as opposed to using Queueable? – Derek F Feb 25 at 17:15
  • Alternatively, can you instead pass enough data to your future method to generate the list of Accounts you want to insert instead of generating them in the synchronous part of the transaction? – Derek F Feb 25 at 17:18
  • I have to create a new classes ( with DAO layer to just do an insert) for that. I was wondering if I could do it simple with a small method of 5-6 lines of code if possible – SfdcBat Feb 25 at 17:18
  • the logic to generate list of Accounts is not in my control. It's been passed to the class. – SfdcBat Feb 25 at 17:19
  • 2
    List<Account> acc = (List<Account>) JSON.deserialize(inp,List<Account>.class); – cropredy Feb 25 at 17:30
2

I do not understand the need to throw this out to a separate transaction? In all honesty you should just insert it once you have the info.

That to one side, the answer to how you deserialize.

@future
public static void createAccount(String inp){
   List<Account> acc = (List<Account>) JSON.deserialize(inp, List<Account>.class);
   insert acc;
}
| improve this answer | |
  • The reason was I have a setup and a non setup object in the same transaction. THanks! – SfdcBat Feb 25 at 17:34
  • Ah that makes sense, no probs. – Crispy Feb 26 at 0:02
4

Future methods are relatively primitive. Consider using a Queueable instead:

List<Account> acList;// I get a list of account from some other method.
System.enqueueJob(new AsyncInsertDml(acList));

Where AsyncInsertDml would be:

public class AsyncInsertDml implements Queueable {
  sObject[] records;
  public AsyncInsertDml(sObject[] source) {
    records = source;
  }
  public void execute(QueueableContext context) {
    insert records;
  }
}

This saves the serialization/deserialization step, and System.enqueueJob lets you get an AsyncApexJob Id that you can check for later to verify if it worked or not.

| improve this answer | |

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.