Tuesday, 18 February 2014

JSON Parser in Salesforce

We hear the term JSON when we are dealing with Integration Projects. Now a days in most of the Integration projects we are using JSON requests or responses.

So it is one of the major area to learn, to become good with Integrations in salesforce.

Salesforce introduces many JSONParser methods to dealing with JSON string in our applications.

Below are few methods mostly used.

JSON.serialize()
Method converts the list of records / string of data to JSON format.

Ex:

List<Account> lstA = [select id,name,phone from Account limit 5];
String strReq = JSON.serialize(lstA);

JSON.deserialize()
Method converts the JSON string to normal format (either stirng / list)

Ex:
List<Account> accountsDeserialized = (List<Account>) JSON.deserialize(strReq, List<Account>.class);

Some times when JSON response are having multi object information we have to use wrapper class to collect the list of data.

Below Sample helps you to understand the use of wrapper class when dealing with JSON.

public with sharing class JSONSerializeCls {
  public List<Account> lstA{get;set;}
  public List<wrapAccCls> lstWA{get;set;}
  public wrapAccCls objWA{get;set;}

         public void JSONserialize(){
            lstA = new List<Account>();
            lstA = [select id,name,phone from Account limit 5];
            String strReq = JSON.serialize(lstA);   // (Or) Response from any callout which is in JSON format
            lstWA = new List<wrapAccCls>();
            objWA = new wrapAccCls();
        
            lstWA = (List<wrapAccCls>)JSON.deserialize(strReq, List<wrapAccCls>.class);
        
            // Convert Wrapper list to Sobject LIst.....

            List<Account> lstA = new List<Account>();
            for(wrapAccCls objWA : lstWA){
                Account objA = new Account();
                objA.Name = objWA.Name;
                 objA.Phone = objWA.Phone;
                 lstA.add(objA);
         }

           if(lstA.size()> 0){
              Insert lstA;
           }
        }
      
        public class wrapAccCls{
           public String ID{get;set;}
           public String Name{get;set;}
           public String phone{get;set;}
   }
}