Showing posts with label Jsonparser. Show all posts
Showing posts with label Jsonparser. Show all posts

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

Sunday, October 9, 2011

Winter 12 New Feature - JSON Support

Hello,

Earlier I used an open source library called JSONObject to parse the json string. It works fine to parse the google json but in some case I was having the following error messaage while parsing the JSON string.

“FATAL_ERROR|superpat.JSONObject.JSONException: Expected a , or }”

You can find solutions of the following error here.

Now in winter 12 release, Salesforce is providing a native support for JSON parsing.

As per the winter 12 release notes -
JSON Support
JavaScript Object Notation (JSON) support has been added. Using JSON classes, you can now parse JSON content and
serialize Apex objects into the JSON format. The following classes have been added for JSON support:
• System.JSON: Contains methods for serializing Apex objects into JSON format and deserializing JSON content that
was serialized using the serialize method in this class.
• System.JSONGenerator: Contains methods used to serialize Apex objects into JSON content using the standard JSON
encoding.
• System.JSONParser: Represents a parser for JSON-encoded content.

You can also find the another cool article on JSON parser here

Thanks,