+ Start a Discussion
raz rraz r 

I want to Parse the below JSON and results should be displayed in VF Page as Accounts with related contacts.

I want to Parse the below JSON and results should be displayed in VF Page as Accounts with related contacts.

JSON:
{"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"}]}}]}

Thanks in Advance!
Balayesu ChilakalapudiBalayesu Chilakalapudi
Create wrdapper class and deserialize your JSON.

WRAPPER CLASS
 
public Main{
public class Wrap{
    public Integer totalSize;
    public boolean done;
    public List<sObject> records;
    public Wrap(integer p_tot,boolean p_done,List<sObject> p_rec){
         totalSize=p_tot;
         done=p_done;
         records=p_rec;
    }
  }
}

now deserialize your JSON like this, place json string in a variable called jsnstrring
 
Main.Wrap w=(Main.Wrap)JSON.deserialize(jsnstrring,Main.Wrap.class);​
raz rraz r
Hi Balayesu ,

Am receiving below error.

Missing dependent object: Class: Riazdev.JSONwrapper.cls_records 

Please asist.
 
raz rraz r
I am getting the wrapper results only |DEBUG|wrapperJsonwrapper:[done=true, records=(Account:{Id=00190000016V11FAAS, Name=birlasoft}), totalSize=1] we are mssing contacts.
Balayesu ChilakalapudiBalayesu Chilakalapudi
I think contacts are missed in the jsonstring itself. you can display the jsonstring and check it out by
System.debug('actual json: '+jsonstring);
raz rraz r
The below is the resposne from callout:
DEBUG|response{"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"}]}}]}

Please assist.
Balayesu ChilakalapudiBalayesu Chilakalapudi
Change the wrapper class as
public class Wrap{
    public Integer totalSize;
    public boolean done;
    public List<Account> records;
    public Wrap(integer p_tot,boolean p_done,List<Account> p_rec){
         totalSize=p_tot;
         done=p_done;
         records=p_rec;
    }
  }

 
raz rraz r
Thie below is the wrpper result am getting.
DEBUG|wrapperJsonwrapper:[done=true, records=(Account:{Id=00190000016V11FAAS, Name=birlasoft}), totalSize=1]

Please assist.
Balayesu ChilakalapudiBalayesu Chilakalapudi
try like this,
public class Wrap{
    public Integer totalSize;
    public boolean done;
    public List<Map<String,Object>> records;
    public Wrap(integer p_tot,boolean p_done,List<Map<String,Object>> p_rec){
         totalSize=p_tot;
         done=p_done;
         records=p_rec;
    }
  }

 
raz rraz r
Its is giving below error

Apex Type unsupported in JSON: Object
Error is in expression '{!getresposnsefromCallout}' in component <apex:commandButton> in page accountswithrelatedcontactsdisplay: Class.System.JSON.deserialize: line 15, column 1
Class.Riazdev.AccountswithReplatedContacts.getresposnsefromCallout: line 26, column 1

  LINE NO:26 : wrapper= (JSONwrapper) System.JSON.deserialize(response, JSONwrapper.class);
 
Balayesu ChilakalapudiBalayesu Chilakalapudi
thy like this,
public class Wrap{
    public Integer totalSize;
    public boolean done;
    public List<Map<String,String>> records;
    public Wrap(integer p_tot,boolean p_done,List<Map<String,String>> p_rec){
         totalSize=p_tot;
         done=p_done;
         records=p_rec;
    }
  }

 
raz rraz r
the below error is came


Illegal value for primitive
Error is in expression '{!getresposnsefromCallout}' in component <apex:commandButton> in page accountswithrelatedcontactsdisplay: Class.System.JSON.deserialize: line 15, column 1
Class.Riazdev.AccountswithReplatedContacts.getresposnsefromCallout: line 26, column 1
 
Balayesu ChilakalapudiBalayesu Chilakalapudi
as per the above link the wrapper class will become
public class Wrap{
    public Integer totalSize;
    public boolean done;
    public List<RecordVO> records;
    public Wrap(integer p_tot,boolean p_done,List<RecordVO> p_rec){
         totalSize=p_tot;
         done=p_done;
         records=p_rec;
    }
  }

and sub class is 
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;
    }
}



 
raz rraz r
Iam getting below error
DEBUG|wrapperJsonwrapper:[done=true, records=(RecordVO:[children=null, recordFields=null]), totalSize=1]
Balayesu ChilakalapudiBalayesu Chilakalapudi
Hi, check out this code, this is tested in my org,
 
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();
        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;
    }
}

 
raz rraz r
How to disply these wrapper results in Pageblock table in vf page ..
raz rraz r
Can you please help me how to move these wrapper results into main class and accounts and contacts would disply in Pageblock table in vf page.
Balayesu ChilakalapudiBalayesu Chilakalapudi
You can get accounts and contacts like this ( tested in my org)
 
//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);



below link will help you to display accounts and contacts in your pageblock table
https://developer.salesforce.com/forums/?id=906F0000000AxfCIAS
raz rraz r
Hi,
I am calling this ParentChildJSON class in another class.but I ddin't get the acclist and conlist into the main class. How to get those lists into Main class.
The below is my main class:

public class AccountswithReplatedContacts {
    public list<Account>acc{get;set;}
    public String Accountname{get;set;}
    public String Response {get;set;}

    public ParentChildJSON pcJson{get;set;}
  
    public  AccountswithReplatedContacts(){
        
        //getresposnsefromCallout();
    }
    
    public void getresposnsefromCallout(){
        //String search=''+Accountname+'';
       // system.debug('searchstring'+search);
String Endpoint='https://'+URL.getSalesforceBaseUrl().getHost()+'/services/data/v39.0/query/?q=SELECT +Id,Name,(select +id,Firstname,Lastname +From+Contacts) +FROM + Account + where + name=\''+String.escapeSingleQuotes(Accountname)+'\'';
         System.debug('Endpoint'+Endpoint);
         HttpRequest req = new HttpRequest();
        req.setMethod('GET');
        string autho = 'Bearer '+userInfo.getSessionId();
        req.setHeader('Authorization', autho);
        req.setEndpoint(Endpoint);
         Http http = new Http();
        HTTPresponse res= http.send(req);
        response = res.getBody();
        system.debug('response'+response);
        
        ParentChildJSON.readJSON(response);
     
        }
    
   
    }
        
      Here , the getresposnsefromCallout method is caling from button in VF page.
Could you please assist.
Thanks!!
Balayesu ChilakalapudiBalayesu Chilakalapudi
make acclist & contlist in ParentChildJSON as top level lists, like
 
public class ParentChildJSON{
     public static list<Account> acclist=new list<Account>();
     public static list<Contact> contlist=new List<Contact>();
....
....
}


inside readJSON initialize them.

you can access them like
 
ParentChildJSON.readJSON(response);
list<Account> acclist=ParentChildJSON.acclist;
list<Contac> contlist=ParentChildJSON.contlist;

 
raz rraz r
Hi,
When I tried to declare as above am getting error like
variable doesnot exist ParentChildJSON.acclist;
variable doesnot exist ParentChildJSON.
contlist;
Please assist.
raz rraz r
Colud you please me assist me on this.
Balayesu ChilakalapudiBalayesu Chilakalapudi
you can hire me on freelancer for fixing your issue, thanks.

https://www.freelancer.in/u/chbalayesu89
Balayesu ChilakalapudiBalayesu Chilakalapudi
https://www.freelancer.in/get/chbalayesu89