Tag Archives: Json

Convert sObject to JSON String and JSON String to sObject Using Apex in Salesforce

Sample Code:

Account acc = new Account(Name = 'Account Name', Phone = '8888888888', Industry = 'Agriculture');
//Code to convert Account to JSON string
String str = JSON.serialize(acc);
system.debug('Account JSON Data - ' + str);
//Code to convert JSON string to Account
Account acc1 = (Account)JSON.deserialize(str, Account.Class);
system.debug('Account Data - ' + acc1);

Output:

Generate Json Data Using Apex in Salesforce

Child Class:

public class Child{

    public String Name;
    
    public Child(String name) {
        this.Name = name;
    }
}

Parent Class:

public class Parent{

    public Child[] ChildRecords;
    public String Name;
    
    public Parent(String Name) {
        this.Name = name;
        ChildRecords = new Child[0];
    }
}

Pass parameters to above class using below code:

//Select Account Id from Account Object
String accountId = '0012800001A4UgG';

//Select Account & Contact Records
Account acc = [SELECT Id, Name, (SELECT Id, Name FROM Contacts) FROM Account WHERE Id =: accountId];

//Create a parent record
Parent par = new Parent(acc.Name);

//Loop on Contacts
for(Contact con: acc.Contacts) {
    par.childRecords.add(new Child(con.Name));
}

//Get the Json data
String jsonData = JSON.serialize(par);
System.debug('JsonData-' + jsonData);

Here is the debug log snapshot of Json data:
Json Data

Note: This is the sample class. You can modify it as per your requirement.

Salesforce Apex JSON Generator

We can generate standard JSON-encoded content, using the JSONGenerator class methods.

JSONGenerator Class Methods:

Method Description
close Closes the JSON generator.No more content can be written after the JSON generator is closed.
getAsString Returns the generated JSON content, and also this method closes the JSON generator if it isn’t closed already.
isClosed Returns true if the JSON generator is closed; otherwise, returns false.
writeBlob Writes the specified Blob value as a base64-encoded string.
writeBlobField Writes a field name and value pair using the specified field name and BLOB value.
writeBoolean Writes the specified Boolean value.
writeBooleanField Writes a field name and value pair using the specified field name and Boolean value.
writeDate Writes the specified date value in the ISO-8601 format.
writeDateField Writes a field name and value pair using the specified field name and date value. The date value is written in the ISO-8601 format.
writeDateTime Writes the specified date and time value in the ISO-8601 format.
writeDateTimeField Writes a field name and value pair using the specified field name and date and time value. The date and time value is written in the ISO-8601 format.
writeEndArray Writes the ending marker of a JSON array (‘]’).
writeEndObject Writes the ending marker of a JSON object (‘}’).
writeFieldName Writes a field name.
writeId Writes the specified ID value.
writeIdField Writes a field name and value pair using the specified field name and identifier value.
writeNull Writes the JSON null literal value
writeNullField Writes a field name and value pair using the specified field name and the JSON null literal value.
writeNumber Writes the specified decimal, double, integer and long value.
writeNumberField Writes a field name and value pair using the specified field name and decimal, double, integer, long value.
writeObject Writes the specified Apex object in JSON format
writeObjectField Writes a field name and value pair using the specified field name and Apex object.
writeStartArray Writes the starting marker of a JSON array (‘[‘).
writeStartObject Writes the starting marker of a JSON object (‘{‘).
writeString Writes the specified string value.
writeStringField Writes a field name and value pair using the specified field name and string value.
writeTime Writes the specified time value in the ISO-8601 format.
writeTimeField Writes a field name and value pair using the specified field name and time value in the ISO-8601 format.

Example:

List<Account> accList = [SELECT Id, Name, AccountNumber, Industry From Account];

if(!accList.isEmpty()){
    JSONGenerator gen = JSON.createGenerator(true);
    gen.writeStartObject();     
    gen.writeFieldName('AccountList');
    gen.writeStartArray();
    for(Account acc :accList){
        gen.writeStartObject();
        gen.writeStringField('Id', acc.Id);
        gen.writeStringField('Name', acc.Name);
        gen.writeStringField('AccountNumber', acc.AccountNumber);
        gen.writeStringField('Industry', acc.Industry);
        gen.writeEndObject();
    }
    gen.writeEndArray();
    gen.writeEndObject();
    String jsonData = gen.getAsString();
    System.debug('jsonData-' + jsonData);
}

Output:

{
  "AccountList" : [ {
    "Id" : "001B000000oAg2fIAC",
    "Name" : "Bostonic Bulk Company",
    "AccountNumber" : "232323",
    "Industry" : "Technology"
  }, {
    "Id" : "001B000000oAg4UIAS",
    "Name" : "Bitrex Bulk Company",
    "AccountNumber" : "123232",
    "Industry" : "Technology"
  }, {
    "Id" : "001B000000pA7skIAC",
    "Name" : "Amazon",
    "AccountNumber" : "12345",
    "Industry" : "Technology"
  }, {
    "Id" : "001B000000pA7sVIAS",
    "Name" : "Salesforce",
    "AccountNumber" : "12346",
    "Industry" : "Technology"
  } ]
}

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);

JSON Response Parsing in Salesforce Apex

We can use the JSONParser class methods to parse JSON-encoded content. The methods of JSONParser class enable to parse a JSON-formatted response that’s returned from a call to an external service, such as a web service callout.

Here is an example of JSON response parsing using apex.

JSON String Data:

{
"ContactList": [
		{
            "FirstName":"Biswajeet",
            "LastName": "Samal",
			"Email": "test1@test.com",
			"Mobile": "9999999999"
        },
        {
            "FirstName":"Abhijeet",
            "LastName": "Samal",
			"Email": "test2@test.com",
			"Mobile": "8888888888"
        }
    ]
}

Apex Class:

//Wrapper Class For Parsering 
public class JsonParseringClass
{
    //Method To Parse JSON Data
    public ContactList getJSONData()
    {
        ContactList conList = new ContactList();
        //JSON String
        String jsonString = '{"ContactList": [' +
            '{"FirstName":"Biswajeet", "LastName": "Samal", "Email": "test1@test.com", "Mobile": "9999999999"},'+
            '{"FirstName":"Abhijeet", "LastName": "Samal", "Email": "test2@test.com",	"Mobile": "8888888888"}]}';
        //Parse JSON to ContactList
        conList = (ContactList)System.JSON.deserialize(jsonstring, ContactList.class);
        System.debug('Respone- ' + conList);
        return conList;
    }
    
    public class ContactList
    {
        public List<ContactWrapper> ContactList;
    }
    
    public class ContactWrapper
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Mobile { get; set; }
    }
}

Debug Log:

Respone- ContactList:[ContactList=(ContactWrapper:[Email=test1@test.com, FirstName=Biswajeet, LastName=Samal, Mobile=9999999999], ContactWrapper:[Email=test2@test.com, FirstName=Abhijeet, LastName=Samal, Mobile=8888888888])]