Generating JSON in Visualforce page in Salesforce

Generating JSON in Visualforce page in Salesforce

JSON stands for “Java Script Object Notation“.

JSON.serialize() is used to generate JSON. It is a lightweight data-interchange
format.

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.

Sample Code:

Visualforce page:

<apex:page controller=”sample” action=”{!parseJson}”>
    {!text1}
</apex:page>

Apex Controller:

public class sample
{   
    public String text1 {get;set;}
     
    public sample()
    {
        
    }   
    public void parseJson()
    {
        String soql = ‘SELECT Name FROM Account LIMIT 5’;
        List<Account> acct = Database.Query(soql);
        text1 = JSON.serialize(acct);
    }   
}

Output:

JSON.deserialize() method is used to deserialize the
specified JSON string into an Apex object of the specified type.

Leave a Reply