function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
JayNicJayNic 

Dynamic Apex question: Submitting a record from JSON string

Hey guys,

 

I have a class that allows users to submit json objects and parses them in to sObjects. It's simpel for strings, and numbers because apex handles those when being assigned to objects. 

 

I'm having trouble finding a good way to handle dates/datetimes.

 

 

 

if(records.size() > 0) {
                        sObjectType s = Schema.getGlobalDescribe().get(sObjectType);
                        list<sObject> objects = new list<sObject>();
                        for(object o : records) {
                            //instantiate a new sObject based on the type specified in the objectMap
                            sObject newRecord = s.newSObject();
                            
                            //Now cast the field mapping definition that the user has passed in to create the record
                            map<string,object> recordDefinition = (map<string,Object>)o;
                            for (string field : recordDefinition.keySet()) {
                                
                                newRecord.put(
                                    field,
                                    recordDefinition.get(field)
                                );
                            }
                            
                            system.debug('UDBG::::insertRecords looped through record and created newRecord: ' + newRecord);
                            objects.add(newRecord);
                        }
                        if(!objects.isEmpty()){
                            insert objects;
                        }
                        responseMessage = objects.size() + ' records inserted';
                        
                    } 

 

Above is my current snippet. Notice that it's all dynamic - the class will allow the user to specify the sObject type - so I figure that out.

 

The "records" variable in the first for loop is an array submitted from json - eg:

[
    {"Name" : "myNewRecordName0", "Type__c" : "MyType0"},
    {"Name" : "myNewRecordName1", "Type__c" : "MyType1"}
]

 I feel like there might be some magic method that can help me out with the next bit... Currently I manually create a new sObject record based on the dynamic type:

 

sObject newRecord = s.newSObject();

Then I just convert each json record to a map, and do a "put" for each field and value with:

                            map<string,object> recordDefinition = (map<string,Object>)o;
                            for (string field : recordDefinition.keySet()) {
                                
                                newRecord.put(
                                    field,
                                    recordDefinition.get(field)
                                );
                            }

 

 

This all works fine until I hit a date, or date time... I have to submit those as strings - eg:

[
    {"Name" : "myNewRecordName0", "Type__c" : "MyType0", "Date__c" : "23-12-2013"},
    {"Name" : "myNewRecordName1", "Type__c" : "MyType1", "Date__c" : "23-12-2013"}
]

 At which point I get the error: 

Illegal assignment from String to Date

 

 

 

SO. Long story short - is there a way I can simply cast my "record" object inteligently to my sObject type? Something like: 

for(object o : records) {
    //instantiate a new sObject based on the type specified in the objectMap
    sObject newRecord = s.newSObject();
    JSON.castSObject(newRecord, o);
}

 

That way I can avoid having to do field type checks on each field and having to cast those individually to the proper field types like "date.valueof("10-10-2013")"

 

 

GlynAGlynA

Check out:

 

public static Object deserialize(String jsonString, System.Type apexType)

 

in the System.JSON class.  Example usage:
 
// Deserialize the list of invoices from the JSON string.
        List<InvoiceStatement> deserializedInvoices = 
          (List<InvoiceStatement>)JSON.deserialize(JSONString, List<InvoiceStatement>.class);
Apparently, it works for lists as well as individual objects.  See the Apex developers guide and search for "JSON roundtrip serialiazation and deserialization".
 
Hope that helps!
-Glyn
 
Shraddha_KhanapureShraddha_Khanapure
Hi JayNic,

Did you get a solution to this problem. I am facing the same issue.

-Shraddha