2

If I have a list of object strings containing field data for an object and I have a parameter selecting which object this should be inserted into, is it possible to write apex to insert those records? From what I understand you need to know the object type upfront so you can do something like this...

//example data
myJSONArr = [{"Subject":"val1","Description":"val2","Status":"val3","Origin":"val4"},{"Subject":"val5","Description":"val6","Status":"val7","Origin":"val8"},{"Subject":"val9","Description":"val10","Status":"val11","Origin":"val12"},{"Subject":"val13","Description":"val4","Status":"val5","Origin":"val16"}]
    
//for Each object element
Case newCase = (Case)JSON.deserialize(myJSONObject, Case);

But is there a way if I had a string with the object name I couldn't somehow...

String selectedObjectToInsert = Case;
<selectedObjectToInsert> = JSON.deserialize(myJSONObject, selectedObjectToInsert);

What should I be looking for to do this sort of dynamic object creation? The end goal is to take the select object, the JSON array of the object fields and values, and insert them into Salesforce.

1 Answer 1

4

If you provide an attributes property, you can deserialize into the generic sObject type, and use that. Here's what that looks like:

sObject a = (sObject)JSON.deserialize('{"attributes":{"type":"Account"}, "Name": "Demo"}', sObject.class);
insert a;

In addition, if you pass in a type, you can use that dynamically:

insertRecords(jsonString, Account.class)

void insertRecords(String jsonString, Type sObjectObjType) {
sObject a = (sObject)JSON.deserialize('{"Name": "Demo"}', sObjectObjType);

Or even:

insertRecords(jsonString, List<Account>.class)

In order to deserialize a list of records.

3
  • Thanks I will try these out and let you know before marking the answer correct.
    – Crash667
    Jun 30, 2023 at 15:38
  • Thanks again this was very helpful. I ended up adding the attributes and using the generic sObject type to successfully insert the list of records.
    – Crash667
    Jun 30, 2023 at 16:43
  • @Crash667 you're welcome!
    – sfdcfox
    Jun 30, 2023 at 18:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .