Friday 4 September 2015

JSON Data Binding in Apex

While playing with JSON I came up with intersting usecase of binding JSON data in Class properties.

Here is JSON Data:
[ 
 {
  "ProductionHouse":"ABCD", 
  "Director":"Mr XYZ", 
  "Casting": [
   { "Title": "Play1", 
   "Artists": ["Artist1", "Artist2", "Artist3", "Artist4", "Artist0"]   
   },    
   {
   "Title": "Play2",
   "Artists": ["Artist1", "Artist2", "Artist0"] 
   }
  ]
 }
]
in order to coupling this data with some real time properties I have written below logic :
 Public Class Play_Controller{

    // JSON data binding with Class properties 
    public static void Databinding()
    {
        String inputJSON= '[    {   "ProductionHouse":"ABCD","Director":"Mr XYZ","Casting": [{ "Title": "Play1","Artists": ["Artist1", "Artist2", "Artist3", "Artist4", "Artist0"]             },  {"Title": "Play2","Artists": ["Artist1", "Artist2", "Artist0"] }]}]';
        List DataMainwrapperList = new List();
        DataMainwrapperList = (List< DataMainwrapper >)JSON.deserialize(inputJSON, List.class);

        for(DataMainwrapper Obj : DataMainwrapperList)
        {
            system.debug('---Prod House Name--'+Obj.ProductionHouse);
            system.debug('---Director--'+Obj.Director);
            for(CastingSubWrapper subobj : obj.Casting)
            {
                system.debug('---Play Title--'+subobj.Title);
                system.debug('---Play Artists--'+subobj.Artists);
            }
        }
    }
    
    // Wrapper holding properties of JSON with data upper leve
    public class DataMainwrapper{
        String ProductionHouse;
        String Director;
        List Casting;
    }

    // Wrapper holding properties of JSON with data sub level
    Public class CastingSubWrapper{
        String Title;
        List Artists;
    }    
}
//--Please Ignore below code line--
Further we can bind this data in respective objects in Apex. So I hope now it will helpful to understand how JSON data may enter in salesforce.

No comments:

Post a Comment