All posts

Salesforce sObject to JSON

This post is about converting a record of any sObject type into JSON. Although this can be done by JSON.Serialize() method but this code can be useful if you want your custom JSON instead of the standard JSON output. For example: You want your fields to be collected under a JSON Field called "Fields" or something else then you can use this code.

ADVANTAGES:
1. No need to create a wrapper.
2. No need to change the code if a new field is added.
3. No need to explicitly write each and every field into JSON.

CODE:
public class sObjectToJSON
{
//This method returns the JSON string for the corresponding record.
public static string createJsonFromSObject(String recordId)
{
//"recordId" can be the Record ID of any object.
if(String.isNotBlank(recordId))
{
String jsonRequest = '';
String queryFields = '';

//Getting the first three characters from the record id and passing that into another method to get the object name.
String objectName = findObjectNameFromRecordIdPrefix(recordId.subString(0,3));

//Getting schema information.
Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();

//Getting the fields information
Map<String, Schema.SObjectField> fieldMap = schemaMap.get(objectName).getDescribe().fields.getMap();

//Initializing a new map to obtain the Data Type of a particular field.
//Key is the Field API name and Value is the Data Type.
Map<String, String> fieldNameTypeMap = new Map<String, String>();

for(Schema.SObjectField sfield: fieldMap.Values())
{
schema.describefieldresult dfield = sfield.getDescribe();

//Putting the field api name and data type into the map.
fieldNameTypeMap.put(dfield.getName(), dfield.getType().name());
}
system.debug('FIELD NAMES-------'+fieldNameTypeMap.keySet().size());
for(String field: fieldNameTypeMap.keySet())
{
//Putting together all the fields to query the data.
queryFields += field+',';
}
queryFields = queryFields.removeEnd(',');

//Creating query in a string variable.
String queryString = 'SELECT '+queryFields+' FROM '+objectName+' WHERE Id =: recordId';
system.debug('QUERYSTRING-----'+queryString);

//Making the query
sObject obj = Database.Query(queryString);
system.debug('OBJECT------'+obj);

//Initializing the JSONGenerator. "true" has been passed into the method for pretty print formatting of JSON.
JSONGenerator gen = JSON.createGenerator(true);
gen.writeStartArray();
gen.writeStartObject();
gen.writeFieldName('attributes'); //creating JSON field "attributes". Change it according to your need.
gen.writeStartObject();
gen.writeStringField('type',objectName);
gen.writeStringField('url','/services/data/v36.0/Sobjects/'+objectName+'/'+recordId);
gen.writeEndObject();
gen.writeFieldName('fields'); //creating JSON field "fields". Change it according to your need.
gen.writeStartObject();

//Iterating over each field and writing every field into JSON string.
//If the field value is null then blank is written in the JSON.
for(String field: fieldNameTypeMap.keySet())
{
if(obj.get(field) != null)
{
gen.writeStringField(field, String.ValueOf(obj.get(field)));
}
else
{
gen.writeStringField(field, '');
}
}

gen.writeEndObject();
gen.writeEndObject();
gen.writeEndArray();
jsonRequest = gen.getAsString();//Getting the JSON String by using "getAsString" method of JSONGenerator class.
system.debug('JSONRequest------'+jsonRequest);
return jsonRequest;
}
else
{
return null;
}
}

//This method returns the name of object by manipulating the record ID.
public static String findObjectNameFromRecordIdPrefix(String recordIdOrPrefix)
{
String objectName = '';
try
{
//Get prefix from record ID
//This assumes that you have passed at least 3 characters
String myIdPrefix = String.valueOf(recordIdOrPrefix).substring(0,3);

//Get schema information
Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();

//Loop through all the sObject types returned by Schema
for(Schema.SObjectType stype : gd.values())
{
Schema.DescribeSObjectResult r = stype.getDescribe();
String prefix = r.getKeyPrefix();

//Check if the prefix matches with requested prefix
if(prefix!=null && prefix.equals(myIdPrefix))
{
objectName = r.getName();
System.debug('Object Name! ' + objectName);
break;
}
}
}
catch(Exception e)
{
System.debug(e);
}
return objectName;
}

}

USAGE:
Lead lead = [SELECT Id FROM Lead LIMIT 1];
String jsonString = sObjectToJSON.createJsonFromSObject(lead.Id);

RESULT:
[{
"attributes": {
"type": "Lead",
"url": "/services/data/v36.0/Sobjects/Lead/00Qm0000004vuWVEAY"
},
"fields": {
"Account__c": "",
"Address1__c": "",
"Address_Country__c": "Canada",
"Address_Type__c": "Home",
"Citizenship_Status__c": "",
"City__c": "",
"Email_Address__c": "go*******sh@gmail.com",
"First_Name__c": "G******h",
"Gender__c": "M",
"Last_Name__c": "Chaudhry",
"Primary_Program__c": "2016-04-22",
"Program_Delivery_Mode__c": "On Campus",
"Program_Specialization__c": "",
"Date_of_Birth__c": "1991-11-11",
"Expected_Start_Date__c": "2017-11-11",
"Advisor_Name__c": "",
"Online_Application_Payment_Confirmation__c": "",
"Campus_Location__c": "Ontario",
"Country_of_Citizenship__c": "",
"YSIS_Student_ID__c": "20***09",
"System_ID__c": "",
"Application_Payment_Type__c": "",
"Application_Fee_Received_Date__c": "",
"Application_Fee_Amount__c": ""
}

}]

First published on Blogger in 2017. Some screenshots and APIs have changed since; the code is kept as written.

  • apex
  • describefieldresult
  • JSON
  • JSONGenerator
  • Salesforce
  • Schema describe
  • sObject
  • sObject to JSON