[SalesForce] Prepare Dynamic JSON body in Apex

I want prepare JSON body dynamically for all the contact fields with mask values, i have queried all the contact fields dynamically assigned to list now i have to prepare JSON body for the fields with mask values.

For example contact name is Anil it should return:

{"Name":"True"}

And if contact Phone is null it should return:

{"Phone":"False"}

How can I achieve this in apex?

Best Answer

Try this. You need to call the createJSON() method You need a wrapper class to cater the requirement like below. Or you may create formula field on the contact for each field and select those fields using SOQL and convert that list to a JSON.

public Class createContactJSON{
    public createContactJSON(){
        createJSON();
    }
    public String createJSON(){
        String JSONstr = '';
        List<Contact> conList = [SELECT Name,Phone FROM Contact];
        List<contactWrapper> conWrapList = new List<contactWrapper>();
        for(Contact tempContact : conList){
            contactWrapper tempcontactWrapper = new contactWrapper();
            tempcontactWrapper.Name = tempContact.Name <> NULL ? true:false;
            tempcontactWrapper.Phone = tempContact.Phone <> NULL ? true:false;
            conWrapList.add(tempcontactWrapper);
        }
        JSONstr = JSON.serialize(conWrapList);
        System.debug('\n******'+JSONstr +'\n******');
        return JSONstr;
    }   
    public class contactWrapper{
        public Boolean Name {get;set;}
        public Boolean Phone {get;set;}
    }
}