I have an Apex class which has a method having an Object type parameter

public with sharing class DmlOnSObjectRecords {
public static void dmlOperationOnSObjectRecords(Object data) {
    List<SObject> recordsForUpdate = (List<SObject>) JSON.deserialize(
    try {
        upsert recordsForUpdate;
    catch (Exception e) {

The parameter given is a JSON in the following format


My problem here is that, the deserialization is throwing me an error

 Nested object for polymorphic foreign key must have an attributes field before any other fields.

I also tried deserializing in the following format

 Map <String, Object> result = (Map <String, Object>) JSON.deserializeUntyped(dataString);

But this also throws an error

 Invalid conversion from runtime type List<ANY> to Map<String,ANY>

I don't want to hard code the type during deserialization because, I want to keep it as a dynamic component.

Also I don't want to use a wrapper class because, then I will have to hard code the paramter fields.


You can pass the type also as a parameter and then deserialize it based on that.

Also pass a string using JSON.stringify in the strJSONdata from UI.

Something like this:

public static void dmlOperationOnSObjectRecords(String strJSONData, String strType, Boolean boolIsList) {
    List<SObject> lstObjects = new List<SObject>();
    if (boolIsList) {
        lstObjects = (List<SObject>) JSON.deserialize(strJSONData, Type.forName(strType));
    } else {
        SObject obj = (SObject) JSON.deserialize(strJSONData, Type.forName(strType));

Anonymous apex:

YourClassName.dmlOperationOnSObjectRecords('{"Id":"0036F00003gZDJQQA4","FirstName":"Madhurima"}', 'Contact', false);

YourClassName.dmlOperationOnSObjectRecords('[{"Id":"0036F00003gZDJQQA4","FirstName":"Madhurima"}]', 'List<Contact>', true);
  • This works, though I would have preferred fetching the Object Type from the record Ids themselves instead of passing the Object type from the js file. Is there absolutely no way to achieve that? @NagendraSingh
    – Madhurima
    Jan 5 at 4:25
  • 1
    Yes there is, but in that case, you need to pass the ID separately instead of the Object Type. Id.valueOf('YOUR_RECORD_ID').getSobjectType().getDescribe().getName() Jan 5 at 4:55
  • hmm, I am actually passing it from a lwc datable, so the only thing I can pass is an Object. No way to separate the editable Ids.
    – Madhurima
    Jan 5 at 9:37
  • I dont think you, you still can, you can just do JSON.stringyfy / JSON.parse and do .Id, that should given you the Id from the row. Jan 5 at 10:34

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.