Related contacts display for Account using JSONGenerator

By | January 10, 2020

Hi, here we have shown how to get the data of related contacts for account using Integration concepts.

Apex Class

public class JSON_Example1 {
    public string accName   	{set;get;}
    public string jsonString  	{set;get;}
    
    public void search(){
        List<Account> accounts = [select id, Name, Phone, Industry, (select LastName, FirstName, Email from contacts) from Account where name=:accName];
        System.JSONGenerator js = JSON.createGenerator(true);
        js.writeStartObject();
        //check weather soql as returned any accounts.
        Integer count = accounts.size();
        if(count>0){
            js.writeStringField('Status', 'Success');
            js.writeNumberField('Records', count);
            js.writeFieldName('Accounts');
            js.writeStartArray();
            for(Account a : accounts){
                js.writeStartObject();
                js.writeStringField('Name', a.Name);
                js.writeStringField('Phone', a.Phone);
                js.writeStringField('Industry', a.Industry);
                list<contact> contacts = a.contacts;
                Integer size = contacts.size();
                if(size>0){
                    js.writeFieldName('Contacts');
                    js.writeStartArray();
                    for(contact con:contacts){
                        js.writeStartObject();
                        js.writeStringField('LastName', con.LastName);
                        js.writeStringField('FirstName', con.FirstName);
                        js.writeEndObject();
                    }
                    js.writeEndArray();
                }
                js.writeEndObject();
            }
            js.writeEndArray();
        }else{
            js.writeStringField('Status', 'Failed');
            js.writeStringField('Error', 'No data found');
        }
        
        js.writeEndObject();
        jsonString = js.getAsString();
    }
}

Vf Page

<apex:page controller="JSON_Example1">
    <apex:form id="fm" >
      <apex:inputText value="{!accName}" />
        <apex:commandButton value="Search" action="{!Search}" reRender="fm" />
        <br/><br/>
        {!jsonString}
    </apex:form>
</apex:page>

Output

Leave a Reply

Your email address will not be published. Required fields are marked *