Tag Archives: sObject

Convert Salesforce sObject Record To JSON

Apex Class:

public class ConvertsObjectToJSON
{
    //Return the JSON string from record Id
    public static string getJsonFromSObject(Id recordId)
    {
        String jsonData = '';
        try{
            if(String.isNotBlank(recordId))
            {
                String sObjectFields = '';
                
                //Get sObject Name
                String objName = recordId.getSObjectType().getDescribe().getName();
                
                //Getting the fields information
                Map<String, Schema.sObjectField> sObjectFieldMap = Schema.getGlobalDescribe().get(objName).getDescribe().fields.getMap();
                
                //Map key is the field API name and value is the field data type.
                Map<String, String> fieldMap = new Map<String, String>();
                
                for(Schema.SObjectField sfield: sObjectFieldMap.Values()){
                    Schema.DescribeFieldResult fieldDesc = sfield.getDescribe();
                    fieldMap.put(fieldDesc.getName(), fieldDesc.getType().name());
                }
                
                //Create query with all fields
                for(String field: fieldMap.keySet()){
                    sObjectFields += field+',';
                }
                sObjectFields = sObjectFields.removeEnd(',');
                
                //Dynamic SOQL Query with all fields
                String soqlQuery = 'SELECT '+ sObjectFields +' FROM '+objName+' WHERE Id =: recordId';
                
                //Execute the SOQL query
                sObject sObj = Database.Query(soqlQuery);
                
                //Create JSON
                JSONGenerator gen = JSON.createGenerator(true);
                gen.writeStartArray();
                gen.writeStartObject();
                gen.writeFieldName('attributes');
                gen.writeStartObject();
                gen.writeStringField('type', objName);
                gen.writeEndObject();
                gen.writeFieldName('fields');
                gen.writeStartObject();
                
                for(String field: fieldMap.keySet()){
                    if(sObj.get(field) != null){
                        gen.writeStringField(field, String.ValueOf(sObj.get(field)));
                    }
                    else{
                        gen.writeStringField(field, '');
                    }
                }
                
                gen.writeEndObject();
                gen.writeEndObject();
                gen.writeEndArray();
                //Getting the JSON String Data
                jsonData = gen.getAsString();
            }
        }
        catch(Exception ex){
            
        }
        return jsonData;
    }
}

Invoke the method:

String jsonData = ConvertsObjectToJSON.getJsonFromSObject('001B000000pA7sV');
system.debug('jsonData-' + jsonData);

Get All Required Fields of sObject Using Apex in Salesforce

Sample Code:

Here in below code I’m getting all required fields of “Account” object.

Map<String, Schema.SObjectType> mapObj  = Schema.getGlobalDescribe();
Schema.SObjectType sObjType = mapObj.get('Account');
Schema.DescribeSObjectResult objDescribe = sObjType.getDescribe();
Map<String,Schema.SObjectField> mapFields = objDescribe.fields.getMap();
List<String> requiredFieldList = new List<String>();

for(String obj : mapFields.keyset()) {
    Schema.DescribeFieldResult describeField = mapFields.get(obj).getDescribe();
    if (describeField.isCreateable()  && !describeField.isNillable() && !describeField.isDefaultedOnCreate()) {
        requiredFieldList.add(obj);
        System.debug(obj);
    }
}

SOQL Query to Select All Fields of sObject

Sample Code:

public class DynamicSOQL {
  public static sObject getAllFieldsData(String objTypeName) {
        sObject sObj;
        Schema.DescribeSObjectResult[] descSObj = Schema.describeSObjects(new String[]{objTypeName});
        Map<String, Schema.SObjectField> fieldMap = descSObj[0].fields.getMap();
        List<String> fieldNames = new List<String>(fieldMap.keySet());
        system.debug('Fields-' + String.join(fieldNames, ','));
        String queryString = 'SELECT '+ String.join(fieldNames, ',') +' FROM '+ objTypeName +' LIMIT 1';
        sObj = Database.query(queryString);
        return sObj;
    }
}

Check Salesforce sObject is Custom or Standard Type

Check for a specific object:

Schema.DescribeSObjectResult objDescribe = Schema.sObjectType.Account;
System.debug(objDescribe.isCustom());

Check for all objects:

List<String> customObjectList = new List<string>();
List<String> standardObjectList = new List<string>();

for(Schema.SobjectType obj : Schema.getGlobalDescribe().values()) {
    Schema.DescribeSObjectResult objDescribe = obj.getDescribe();
    if(objDescribe.isCustom()) {
        String objName = objDescribe.getName();
        customObjectList.add(objName);
    }
    else {
        String objName = objDescribe.getName();
        standardObjectList.add(objName);
    }
}

System.debug('Custom Object List - ' + customObjectList);
System.debug('Standard Object List - ' + standardObjectList);