Sunday 25 January 2015

Using JSON.deserializeUntyped to create dynamically records from JSON

Few days ago, got a requirement of the webservice for the creation of the records from the data in the JSON response. Tried some old fashioned code that use object instance to insert the records, but I was not feeling to fulfill to use that one.

So I started doing some search on JSON de-serializing method of salesforce and then I got this one.
In the starting this method seems to be not that much helping, but later one found out that "deserializeUntyped" is one of the best method for JSON de-serialization.

Code Scope : This below code will dynamically create Salesforce Object records without specifying their instance in the code and field specified in the json response will be responsible for the field value of the records.
Its a generic code that can be used whenever you are creating a webservice for the creation of the records in Salesforce.

Here is code...

1:  public class DynamicRecordCreationFromJSONResponse {  
2:    
3:       public static void parseJSONCreateRecords() {  
4:              
5:            String jsonInput = '{\n' +  
6:                                  ' "Account" : [ ' +   
7:                                                            '{"Name":"Sample Account","CustomField__c":"BR22RRR","CustomBooleanField__c":true,"Lookup_Field__c":"a08g0000006c9EH"}, \n' +  
8:                                                            '{"Name":"Sample Account2","CustomField__c":"Peroni"} ],\n' +  
9:                                     ' "CustomObject__c" : [ ' +   
10:                                                            '{"Name":"Sample Record 1"}, \n' +  
11:                                                            '{"Name":"Sample Record 2","Activity_Description__c":"Testing"} ]\n' +  
12:                                     '}';  
13:              
14:            // Parse entire JSON response using deserializeUntyped  
15:         Map<String, Object> mapOfNameWithRecords = (Map<String, Object>)JSON.deserializeUntyped(jsonInput);  
16:            System.debug('mapOfNameWithRecords::::::::' + mapOfNameWithRecords.keySet());  
17:              
18:            //List of Objects  
19:            List<sObject> objList = new List<sObject>();  
20:            Map<String, List<String>> fieldswithDataType = new Map<String, List<String>>();  
21:                             
22:            //Loop through mapOfNameWithRecords  
23:            for(String objName : mapOfNameWithRecords.keySet()) {  
24:                   
25:                 //process to get the name of the object by removing curly braces  
26:                 String str = objName.replace('{',' ');  
27:                 String finalstr = str.replace('}',' ');  
28:                 finalstr = finalstr.trim();  
29:                   
30:                 //Get the records of the object from the json  
31:                 List<Object> recordList = (List<Object>)mapOfNameWithRecords.get(finalstr);  
32:                 System.debug('recordList::::::::' + recordList);  
33:              
34:                 //Loop through the list of records of JSON  
35:                 for(Object obj : (List<Object>)mapOfNameWithRecords.get(finalstr)) {  
36:                        
37:                      //Create new sObject instance  
38:                      SObject sobjectInstance = Schema.getGlobalDescribe().get(finalstr).newSObject();  
39:                        
40:                      //Populating map with field name and values  
41:                      Map<String, Object> a2 = (Map<String, Object>)obj;  
42:                        
43:                      //Loop through the keySet  
44:                      for(String st : a2.keySet()) {  
45:                           sobjectInstance.put( st, a2.get(st));  
46:             }  
47:                        
48:                      //Add to list of sObjectk  
49:                      objList.add(sobjectInstance);  
50:                 }  
51:            }  
52:            System.debug('objList::::::::' + objList);  
53:              
54:            //Check for list size and insert  
55:            if(objList.size() > 0) {  
56:                 insert objList;  
57:            }  
58:       }  
59:  }  

Note : Date formate should be taken care of as it varies from Local of Salesforce User, so do provide right format for the Date and Date Time fields.

Thanks
Happy Coding...cheers!!!


2 comments:

  1. Very nice!! Look forward to seeing more.

    ReplyDelete
    Replies
    1. Thank you Jeff, now this post is worth of something :) #greatfan

      Delete