Wednesday, November 9, 2011

How to parse JSON string using JSONParser class in Salesforce

Sample JSON String -
[ {  "Id" : "003U0000002kq41IAA", "FirstName" : "Rose", "LastName" : "Gonzalez", "Email" : "rose@edge.com", "Title" : "SVP, Procurement" }, {  "Id" : "003U0000002kq42IAA", "FirstName" : "Sean", "LastName" : "Forbes", "Email" : "sean@edge.com", "Title" : "CFO" }, {  "Id" : "003U0000002kq43IAA", "FirstName" : "Jack", "LastName" : "Rogers", "Email" : "jrogers@burlington.com", "Title" : "VP, Facilities" }, {  "Id" : "003U0000002kq44IAA", "FirstName" : "Pat", "LastName" : "Stumuller", "Email" : "pat@pyramid.net", "Title" : "SVP, Administration and Finance" }, {  "Id" : "003U0000002kq45IAA", "FirstName" : "Andy", "LastName" : "Young", "Email" : "a_young@dickenson.com", "Title" : "SVP, Operations" } ] 
Apex Class to parse JSON String -
public class JSONParserController{
    
    public List<ContactInfo> lstContactInfo{get;set;}
    public JSONParserController(){
        try{
            String jsonString = '[ {  "Id" : "003U0000002kq41IAA", "FirstName" : "Rose", "LastName" : "Gonzalez", "Email" : "rose@edge.com", "Title" : "SVP, Procurement" }, {  "Id" : "003U0000002kq42IAA", "FirstName" : "Sean", "LastName" : "Forbes", "Email" : "sean@edge.com", "Title" : "CFO" }, {  "Id" : "003U0000002kq43IAA", "FirstName" : "Jack", "LastName" : "Rogers", "Email" : "jrogers@burlington.com", "Title" : "VP, Facilities" }, {  "Id" : "003U0000002kq44IAA", "FirstName" : "Pat", "LastName" : "Stumuller", "Email" : "pat@pyramid.net", "Title" : "SVP, Administration and Finance" }, {  "Id" : "003U0000002kq45IAA", "FirstName" : "Andy", "LastName" : "Young", "Email" : "a_young@dickenson.com", "Title" : "SVP, Operations" } ] ';
            parseJSON(jsonString);
        }
        catch(Exception e ){
            Apexpages.addMessages(e);
        }
    }
    
    public void parseJSON(String jsonstr){
        if (jsonstr != null){
        lstContactInfo= new List<ContactInfo>();   
        JSONParser parser = JSON.createParser(jsonstr);
        while (parser.nextToken() != null)
        {
            if (parser.getCurrentToken() == JSONToken.START_ARRAY)
            {
             
                while (parser.nextToken() !=  JSONToken.END_ARRAY)
                {
                    if (parser.getCurrentToken() == JSONToken.START_OBJECT)
                    {
                        
                        ContactInfo ci = new ContactInfo();
                        while (parser.nextToken() !=  JSONToken.END_OBJECT)
                        {
                            
                                if((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&(parser.getText().tolowercase() == 'title'))
                                {
                                    parser.nextToken() ;    
                                    ci.title = parser.getText();
                                }
                                if((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&(parser.getText().tolowercase() == 'firstname'))
                                {
                                    parser.nextToken()     ;
                                    ci.firstname = parser.getText();
                                }
                                if((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&(parser.getText().tolowercase() == 'lastname'))
                                {
                                    parser.nextToken()     ;
                                    ci.lastname = parser.getText();
                                }
                                if((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&(parser.getText().tolowercase() == 'email'))
                                {
                                    parser.nextToken()     ;
                                    ci.email = parser.getText();
                                }
                           
                            
                        }
                        lstContactInfo.add(ci);
                    }
                }
            }
        }
      }   
    }
    
    public class ContactInfo{
        public string title{get;set;}
        public string firstName{get;set;}
        public string lastName{get;set;}
        public string email{get;set;}
        public ContactInfo(){
        
        }
    }
}

Show response on VF Page -
<apex:page controller="JSONParserController">
  <apex:form >
      <apex:pageBlock >
      
          <apex:pageBlockSection >
              <apex:pageBlockTable value="{!lstContactInfo}" var="item">
                  <apex:column value="{!item.title}" headerValue="Title"/>
                  <apex:column value="{!item.firstname}" headerValue="First Name"/>
                  <apex:column value="{!item.lastname}" headerValue="Last Name"/>
                  <apex:column value="{!item.email}" headerValue="Email"/>
              </apex:pageBlockTable>
          </apex:pageBlockSection>
      </apex:pageBlock>
  </apex:form>
</apex:page>

Please refer the following link to complete documentation for JSONParser class methods.
http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_jsonparser.htm

2 comments:

  1. Thank you so much for this code... It is really helpful.

    ReplyDelete
  2. Hi Dev,

    Could you pls help me to parse below json, how can I create parser for it.
    Thanks!

    {"educations": {
    "_total": 2,
    "values": [
    {
    "activities": "Debate team",
    "degree": "Bachelor of Commerce (B.Com.)",
    "endDate": {"year": 2014},
    "fieldOfStudy": "",
    "id": 219318342,
    "schoolName": "The University of Texas at Austin",
    "startDate": {"year": 2010}
    },
    {
    "endDate": {"year": 2007},
    "id": 219316871,
    "schoolName": "University of California, Los Angeles",
    "startDate": {"year": 2005}
    }
    ]
    }}

    ReplyDelete