New Batch#100 (10th Nov 2021) - Salesforce Admin + Dev Training (WhatsApp: +91 - 8087988044) :https://t.co/p4F3oeQagK

Friday, 9 February 2018

Apex Method to convert json format records into List of Sobject Records format


The following method will be useful when you are supplying list of records as input to the Apex Method.

Note:
1. Passing List of Sobjects to the Apex Method from the Lightning component is not allowed.
2. you should convert Sobject list by using JSON.stringify(yourSobjects) and the Apex method input should be string.
3. The following method will be useful to convert above json fromat string into List<Sobject>

Please find the following Code -

/*** Method to convert json format records into List of Sobjects ***/
public static List<Sobject> convertJsonToSobjectLst(String json) {
List<object> objects = (List<object>)System.JSON.deserializeUntyped(json);
List<SObject> sobjRecordsLst = new List<SObject>();
for (Object obj : objects) {
Map<String, Object> m = (Map<String, Object>)obj;
String key = (String)m.get('SobjectType');
key = key.toLowerCase();
Schema.SObjectType targetType = Schema.getGlobalDescribe().get(key);
SObject sObj = targetType.newSObject();
Map<String, Schema.SObjectField> fields = targetType.getDescribe().fields.getMap();
for (String fieldName : m.keySet()) {
// Filter out any psuedo fields such as LastNameLocal
Schema.SObjectField fld = fields.get(fieldName);
if (fld != null) {
if (fld.getDescribe().isCreateable() && fld.getDescribe().isUpdateable()) {
sObj.put(fieldName, m.get(fieldName));
}
}
}
sobjRecordsLst.add(sObj);
}
return sobjRecordsLst;
}
Thank You,
http://onlinetraining.srinusfdc.com/

1 comment:

  1. My spouse and I love your blog and find almost all of your post’s to be just what I’m looking for.
    safety course in chennai
    nebosh course in chennai

    ReplyDelete