Thursday, 22 February 2018

Salesforce - Serialize/deserialize Parent and child records

JsonString will be like


{"totalSize":1,"done":true,"records":[{"attributes":{"type":"Account","url":"/services/data/v39.0/sobjects/Account/00190000016V11FAAS"},"Id":"00190000016V11FAAS","Name":"birlasoft","Contacts":{"totalSize":6,"done":true,"records":[{"attributes":{"type":"Contact","url":"/services/data/v39.0/sobjects/Contact/0039000002MYh46AAD"},"Id":"0039000002MYh46AAD","Name":"Krishna K"},{"attributes":{"type":"Contact","url":"/services/data/v39.0/sobjects/Contact/0039000002MYgxfAAD"},"Id":"0039000002MYgxfAAD","Name":"Krishna K"},{"attributes":{"type":"Contact","url":"/services/data/v39.0/sobjects/Contact/0039000002MYgXrAAL"},"Id":"0039000002MYgXrAAL","Name":"Riaz Test"},{"attributes":{"type":"Contact","url":"/services/data/v39.0/sobjects/Contact/0039000002MYhF4AAL"},"Id":"0039000002MYhF4AAL","Name":"Deepika HR"},{"attributes":{"type":"Contact","url":"/services/data/v39.0/sobjects/Contact/0039000002MYhHoAAL"},"Id":"0039000002MYhHoAAL","Name":"Romit Shilpe"},{"attributes":{"type":"Contact","url":"/services/data/v39.0/sobjects/Contact/0039000001AlZ2XAAV"},"Id":"0039000001AlZ2XAAV","Name":"Riazgood boy"}]}}]}




To process the above jsonString, below class will be useful

public class ParentChildJSON {
    public static void readJSON(){
        //I have stored the response jsonString in a static resource called ParentChildJSON
       // StaticResource srObject = [select id,body from StaticResource Where Name = //'ParentChildJSON'];
        //replace jsonString here
       //String jsonString = srObject.body.toString();
        String jsonString='';
        System.debug('jsonString: '+jsonString);
        //get the json in a map
        Map<String,Object> mp=(Map<String,Object>)JSON.deserializeUntyped(jsonString);
        String acc_cont_json='';
        //get accounts with contacts here
        for(String ky:mp.keySet()){
            if(ky.equals('records')){
                acc_cont_json=JSON.serialize(mp.get(ky));
            }
        }
        //now get accounts
        RecordVO[] rvos = getdeserializeSObjects(acc_cont_json);
        System.debug('total accounts: '+rvos.size());
        System.debug('accounts: '+rvos[0].recordFields);
        System.debug('contacts: '+rvos[0].children);
    } 
    public static RecordVO[] getdeserializeSObjects(String jsonString)
    {
        Object[] recObjects = (Object[])JSON.deserializeUntyped(jsonString);
        return serializeObjects(recObjects);
    }
    public static RecordVO[] serializeSObjects(SObject[] recs)
    {
        Object[] recObjects = (Object[])JSON.deserializeUntyped(JSON.serialize(recs));
        return serializeObjects(recObjects);
    }
 
    public class RecordVO
    {
        public Map<String, Object> recordFields { get; set; }
        public RecordVO[] children { get; set; }
     
        public RecordVO(Map<String, Object> fields, RecordVO[] ch)
        {
            recordFields = fields;
            children = ch;
        }
    }
 
    private static RecordVO[] serializeObjects(Object[] recObjects)
    {
        RecordVO[] rvos = new RecordVO[]{};
         
            // loop over each record
            for (Object recObj : recObjects)
        {
            Map<String, Object> recordFields = new Map<String, Object>();
            RecordVO[] children = new RecordVO[]{};
             
                // loop over each field or children
                Map<String, Object> objMap = (Map<String, Object>)recObj;
            for (String attr : objMap.keyset())
            {
                if (attr != 'attributes')
                {
                    // get children if applicable
                    if (objMap.get(attr) instanceof Map<String, Object>)
                    {
                        Object childObj = ((Map<String, Object>)objMap.get(attr)).get('records');
                        Object[] childObjList = (Object[])childObj;
                        if (childObjList != null)
                        {
                            RecordVO[] childrenVOs = serializeObjects(childObjList);
                            children.addAll(childrenVOs);
                        }
                    }
                    else
                    {
                        recordFields.put(attr, objMap.get(attr));
                    }
                }
            }
         
            rvos.add(new RecordVO(recordFields, children));
        }
     
        return rvos;
    }
}












call will be like,

ParentChildJSON.readJSON();




 //now get accounts & contacts
        RecordVO[] rvos = getdeserializeSObjects(acc_cont_json);
        System.debug('total accounts: '+rvos.size());
        System.debug('accounts: '+rvos[0].recordFields);
        System.debug('contacts: '+rvos[0].children);
        List<Account> acclist=new List<Account>();
        List<Contact> contlist=new List<Contact>();       
        for(RecordVO rvo:rvos){ 
            //add accounts
            acclist.add(new Account(Id=String.valueOf(rvo.recordFields.get('Id')),
                                    Name=String.valueOf(rvo.recordFields.get('Name'))));
            //add all contacts
            for(RecordVO vo:rvo.children){
                contlist.add(new Contact(Id=String.valueOf(vo.recordFields.get('Id')),
                                         FirstName=String.valueOf(vo.recordFields.get('Name'))));
            }
        }
        System.debug('acclist: '+acclist);
        System.debug('contlist: '+contlist);





No comments:

Post a Comment