When the new Apex type methods were added in Summer ’12, it was possible to do
Type t = Type.forName('MyClass'); MyClass newObj = (MyClass)t.newInstance();
What is the equivalent when I want to instantiate a List of such a class for which I only know the name at runtime?
I am also trying to create multiple records using
JSON.deserialize
. I think the answer to the earlier question may also help me with creating a List of such objects withJSON.deserialize(jsonStringOfSeveralObjects, appropriateListClass)
.Note: I am able to use a Type method to create a record of a custom object like this:
Type oType = Type.forName(‘MySobjectName’); sObject rec = (sObject) JSON.deserialize(jsonString, oType);
But when the JSON string is an array of objects I am unable to use a method similar to the example shown below:
List<InvoiceStatement> deserializedInvoices = (List<InvoiceStatement>)JSON.deserialize(JSONString, List<InvoiceStatement>.class);
Can you suggest the right format to use with
List<>
to create multiple records? I am specifically looking for corresponding substitutes forList<InvoiceStatement>
andList<InvoiceStatement>.class
that can be dynamically determined.
Answer
The trick is to deserialize into a List<SObject>
. This works for me:
String jsonString = '[{"Name":"A1"},{"Name":"A2"}]';
Type t = Type.forName('List<Account>');
List<SObject> lo = (List<SObject>)JSON.deserialize(jsonString, t);
for (SObject o : lo) {
System.debug(o.getSObjectType().getDescribe().getName() + ', Name: ' + o.get('Name'));
}
Output:
Account, Name: A1
Account, Name: A2
Attribution
Source : Link , Question Author : metadaddy , Answer Author : metadaddy