JSON output in Visualforce

Author posted by Jitendra on Posted on under category Categories Apex, Salesforce, Visualforce and tagged as Tags , , with 8 Comments on JSON output in Visualforce

The Example of generating the JSON Output in Visualforce page using JSON.serialize method provided by Salesforce

In this article, i will demonstrate using the JSON.serialize() method provided by the Salesforce to convert the class into equivalent JSON String.

Before going into depth would like to explain the basic concept of JSON syntax for the newbie.

There are following thumb rules i have identified from my experience, please comment in this article if i miss something here:

  • The JSON stands for “Java Script Object Notation“.
  • JSON is used widely as an option to xml, because the xml is very verbose whereas the JSON is having very simple representation.
  • It Simply have a key and value pair combination.
  • DataTypes supported by the JSON are “Number, String, Boolean, Array, Object and null”.
  • Key and value pair are separated by colon “:”
  • Object is enclosed between curly brackets “{” and “}”.
  • Array is enclosed using square bracket “[“, “]” separated by the comma.

Example of JSON syntax:

{
     "firstName": "Jitendra",
     "lastName" : "Zaa",
     "age"      : 26,
     "address"  :
     {
         "streetAddress": "21 2nd Street",
         "city"         : "Nagpur",
         "state"        : "MH",
         "postalCode"   : "400008"
     },
     "phoneNumber":
     [
         {
           "type"  : "Mobile",
           "number": "212 555-1234"
         },
         {
           "type"  : "Home",
           "number": "646 555-4567"
         }
     ]
 }

Download Source code – Visualforce page as JSON

Now i hope that you must have got some starting information regarding the JSON syntax.
I am taking example of room reservation system and going to create classes in Apex and then convert all into equivalent JSON code. Following is the structure of class i need for this demo.

  • ReservationDetail (This class will have information like start and end time of room, description and label)
  • Room (This class have room and list of above class as one room can be booked by multiple users).

Refer Salesforce – JSON API

Below is the complete code of the Apex class to generate the JSON.

/**
	Author - Jitendra Zaa
	This controller class is used by the VF page "GanttChartData" to generate the JSON
*/
public with sharing class GanttChartData {

	public String jsonString {get;set;}

	//Constructor
	public GanttChartData()
	{
		jsonString = prepareData();

	}
	//Temp Method to prepare the Data
	private String prepareData()
	{
		List<ReservationDetail> dtlObj = new List<ReservationDetail>();

		ReservationDetail obj1 = new ReservationDetail();
		ReservationDetail obj2 = new ReservationDetail();
		ReservationDetail obj3 = new ReservationDetail();

		obj1.setFromDate(String.valueOf(datetime.newInstanceGmt(2012,04, 17, 0, 0, 0).getTime()));
		obj1.setToDate(String.valueOf(datetime.newInstanceGmt(2012,04, 17, 05, 30, 0).getTime()));
		obj1.desc_PH = 'Booked by : Jitendra <br /> for JQuery Demo';
		obj1.label = 'Jitendra';
		obj1.customClass = 'ganttRed';

		obj2.setFromDate(String.valueOf(datetime.newInstanceGmt(2012,04, 17, 20, 30, 0).getTime()));
		obj2.setToDate(String.valueOf(datetime.newInstanceGmt(2012,04, 17, 23, 30, 2).getTime()));
		obj2.desc_PH = 'Booked by : Tuiya <br /> for Wireless Lecture';
		obj2.label = 'Tuiya';
		obj2.customClass = 'ganttOrange';

		obj3.setFromDate(String.valueOf(datetime.newInstanceGmt(2012,04, 19, 09, 30, 0).getTime()));
		obj3.setToDate(String.valueOf(datetime.newInstanceGmt(2012,04, 19, 16, 30, 2).getTime()));
		obj3.desc_PH = 'Booked by : Santosh <br /> for SAP Basis';
		obj3.label = 'Santosh';
		obj3.customClass = 'ganttGreen';

		dtlObj.add(obj1);
		dtlObj.add(obj2);
		dtlObj.add(obj3);

		Room r = new Room();
		r.name = 'Training Room';
		r.desc_PH = 'This is Training Room';
		r.values = dtlObj;

		List<Room> r1 = new List<Room>();
		r1.add(r);

		return JSON.serialize(r1);
	}
	public class RoomList
	{
		public List<Room> rooms;
	}
	public class Room
	{
		public String name{get;set;}
		//Below var name - desc
		public String desc_PH{get;set;}
		public List<ReservationDetail> values{get;set;}
	}

	public class ReservationDetail
	{
		//actual variable name needed was "from", but it is keyword so we cant use that
		public String frm_PH{get;set;}
		public String to{get;set;}

		public String desc_PH{get;set;}
		public String label{get;set;}

		/*
			Custom class Can be anything from below:
			ganttRed
			ganttGreen
			ganttOrange

		*/
		public String customClass{get;set;}

		public void setToDate(String val)
		{
			to = setDate(val);
		}
		public void setFromDate(String val)
		{
			frm_PH = setDate(val);
		}
		//Date should be in special format as it is used in regular expression
		private String setDate(String val)
		{
			return '/Date('+val+')/';
		}
	}
}

As you can see in above code that i am using method “JSON.serialize(Object)” to convert the class into JSON. the variable name will be converted as a key.

In above code some extra logic is also added like formatting Date data, there is no need of this.

Output Visualforce page as JSON Data:

To output the Visualforce page as JSON Data following point needs to be taken care,

  1. contentType should be “application/x-JavaScript; charset=utf-8” (Note that i have not specified it as json although valid MIME type available for JSON in HTML)
  2. showHeader attribute should be false.
  3. standardStylesheets attribute should be false.
  4. sidebar attribute should be false.
  5. While calling the VF page always specify explicitly that we don’t need Page editor tool of the Salesforce using core.apexpages.devmode.url=0.

Source code for VF:

<apex:page controller="GanttChartData"  contentType="application/x-JavaScript; charset=utf-8" showHeader="false" standardStylesheets="false" sidebar="false">
{!jsonString}
</apex:page>

The output of the above code is:

Visualforce page output as JSON
Visualforce page output as JSON

Download Source code – Visualforce page as JSON

Related posts

  • Pingback: Gantt Chart in Salesforce using JQuery and JSON | Shiva Blog()

  • Supriya Soni

    Hi,

    Thanks for the nice code.

    But i would like to correct one thing –

    use  return JSON.serializePretty(r1); instead of JSON.serialize(r1);

    to get formatted output.

    • JitendraZaa

      Thanks Supriya…
      However there will be no impact on functionality by using anyone of them.

  • Great tutorial– came up in google for me to augment my meeting with an SFDC dev perfectly. Thanks for sharing!

  • Dipak

    Hi Jitendra,
    Thanks for the post. Very nicely presented the tutorial. Easy to understand.

    Cheers

  • Pingback: AJAX Based AutoComplete Component in Salesforce Using JQuery UI and JSON | Shiva Blog()

  • Veasna

    Hello Jitendra,
    Could you please provide example on how to Serialize JSON from a custom Object and manipulate you GanttChartData class to draw the chart?

    Query List ie. List Projects = [SELECT Name, Start_Date__c, Expected_Date__c FROM Projects__c LIMIT 200];

    set Name = desc
    set Start_Date__c = from
    set Expected_Date__c = to

  • sonu soni

    hi jitendra,

    Thanks for code, very nice code.