System.NullPointerException: Attempt to de-reference a null object in JSON Parsing Salesforce.

 

Salesforce Solutions

System.NullPointerException: Attempt to de-reference a null object in JSON Parsing Salesforce.


The above error occurs in the JSON parsing Scenario.

When Error Occur:-


                This error has been produced when we were parsing the JSON.


Why

Below JSON is returned in the API Call.

{"menu": {  

  "id": "file",  

  "value": "File",  

  "popup": {  

    "menuitem": [  

      {

          "value": "New",

          "onclick": "CreateDoc()"

      },  

      {

          "value": "Open",

          "onclick": "OpenDoc()"

      },  

      {

          "value": "Save", 

          "onclick": "SaveDoc()"

      }  

    ]  

  }  

}}


Below is the Apex method to Parse the JSON:-


public class ReadJsonFile {

    

    public void readJsonFile() {

        

        String apiKey='**************************';

        

        String requestEndPoint='http://api.openweathermap.org/data/2.5/weather';

        requestEndPoint+='?q=jaipur';

        requestEndPoint+='&units=metric';

        requestEndPoint+='&APPID='+apiKey;

        

        Http http = new Http();

        HttpRequest request=new HttpRequest();

        request.setEndpoint(requestEndPoint);

        request.setMethod('GET');

        System.HttpResponse response=http.send(request);

        

        if(response.getStatusCode() == 200)

        {

            Main res = (Main)System.JSON.deserialize(response.getBody(), Main.class);

            List<ExampleArr> items = res.menu1.popup.menuitem;

            for(ExampleArr menuitems : items){

                if(menuitems.value == 'Open')

                    system.debug(menuitems.onclick);

            }

        }    

    }

}



We have to create classes for parsing the JSON.


public class Main {

    public ResponseResult menu1;

}



public class ResponseResult {

    

    public String id;

    public String value;

    public Result popup;

}



public class Result {

    public List<ExampleArr> menuitem;

}



public class ExampleArr {

public String value;

    public String onclick;

}



We can see that in the above call the menu1 reference variable in the Main class of type ResponseResult.



Solution - 


Our API is returning the main node in the JSON response so we should declare the variable with the same name in the Wrapper class.

To fix this, we only need to modify our Main  apex class like below


public class Main {

    public ResponseResult menu;

}




#salesforce 

#salesforcesolution

 #salesforcedeveloper

 #salesforceJSONParsing

 #salesforceJSONParsingError 



Comments

Popular posts from this blog

Send Email through Pardot API in Salesforce Apex

HOW TO GET LARGE SETS OF DATA USING BULK API IN SALESFORCE THROUGH WORKBENCH