JSON Output using VisualForce

While working on modern technologies – lot of time you would need to either consume JSON data in your application or generate JSON data/output from your applications . As a refresher – JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

In this post – I am quickly going to show how you can generate JSON output from your Visual force page. Below is the VF and APEX code for rendering the output as JSON. In the custom controller, I am building a list of Billing Statements and then utilizing the ‘JSON.serialize()‘ method which serializes input Apex objects into JSON string. The entire process is invoked during the controller object creation as it is being called from the constructor of the outer class. The VF page is simply displaying the content of the String variable ‘jsonStr‘. In the VF page, I have removed the standard Salesforce header, sidebar and stylesheets to keep the page clean and let only the JSON string to appear.

Click here for demo


Feel Free to provide your valuable comments or point out any issues or scope of improvement in this post.