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 - ' + strJSON);
//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.

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

JSON

Biswajeet   May 3, 2014   No Comments on JSON

JSON (JavaScript Object Notation) is a lightweight and text-based data-interchange format. Supports with UTF-8 and date-time information in ISO8601 format. It uses string value pairs for storing data.

Basically it is used to transmit data between a browser and a server. When exchanging data between a browser and a server, the data can only be text. JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server.

Example:

{
   "firstName":"Biswajeet",
   "lastName":"Samal",
   "isAlive":true,
   "age":28,
   "address":{
      "streetAddress":"25 2nd Street",
      "city":"New York",
      "state":"NY",
      "postalCode":"10021-3100"
   },
   "phoneNumbers":[
      {
         "type":"home",
         "number":"212 888-1234"
      },
      {
         "type":"office",
         "number":"646 989-4567"
      },
      {
         "type":"mobile",
         "number":"123 456-7890"
      }
   ],
   "children":[

   ],
   "spouse":null
}

JSON supports following data types:

  • string
  • {"name":"Biswajeet Samal"}
  • number
  • {"age":28}
  • object
  • {
    "employee":{ "name":"Biswajeet Samal", "age":28, "city":"London" }
    }
  • array
  • {
    "employees":[ "Biswajeet", "Abhijeet", "Satyajeet" ]
    }
  • boolean
  • {"isAlive":true}
  • null
  • {"spouse":null}