Implement JSON in Apex #inSalesforce

Implement JSON in Apex #inSalesforce


Serialize Apex objects into JSON format and deserializing JSON content that was serialized using the serialize method in this class


Example:


JSONController 
public with sharing class JSONController { 
    public list<Account> acct { get{
        acct = [Select Id,Name,AccountNumber,AccountSource from Account where name != null limit 50000];
        if(acct == null){
            acct = new list<Account>();   
        }
        return acct;
    } set;}   
    public string jsonSerial {get{
        if(acct == null){
            jsonSerial = '';   
        }else{
            jsonSerial = JSON.serialize(acct);
        }
        return jsonSerial;
    } set; }
    public string jsonGenr { get{
        JSONGenerator gen = JSON.createGenerator(false);
        if(acct == null){
            return ''; 
        }else{
            gen.writeStartArray();
            for(Account a: acct){
                gen.writeStartObject();
                gen.writeStringField('Name', a.name);
                gen.writeStringField('Id', a.Id);
                if(a.AccountNumber==null)
                    gen.writeStringField('Account Number', '');
                else{
                    gen.writeStringField('Account Number',a.AccountNumber); 
                }
                gen.writeEndObject();
            }
            gen.writeEndArray();
            return gen.getAsString();
        }
    } set; } 
}



VF Page:

<apex:page controller="JSONController">
    <apex:form>
        <strong>Output through the list in data table</strong>:<br/><br/>
        <apex:dataTable value = "{!acct}" var = "key">
            <apex:column>
                <apex:facet name = "header">Name</apex:facet>
                {!key.Name}
            </apex:column>
            <apex:column>
                <apex:facet name = "header">Number</apex:facet>
                {!key.AccountNumber}
            </apex:column>
        </apex:dataTable>
        <br/>
        <strong>From serialize method </strong> :<br/><br/> {!jsonSerial}
        <br/>
        <strong>From JSON Generator method </strong> :<br/><br/> {!jsonGenr}
    </apex:form>
</apex:page>





Comments