In this example had shown only 2 fields, Need to handle many fields. For checking, null pointer exception for each fields are really tedious Task. Any Easy way to do this.

Apex Class:

public class RequestWrapper {
  public class RequestHandler{
  public RequestResponseHandler request;
//Created separte wrapper for request
  public class ResponseHandler{
    public RequestResponseHandler response;
  //In My case : Request and response both are same
  public class RequestResponseHandler{
      public String  enddate;
      public String name;

Integration Code:

    HTTPResponse response = http.send(req);
    if (response.getStatusCode() == 200){
        RequestWrapper.RequestResponseHandler result = (RequestWrapper.RequestResponseHandler)System.JSON.deserialize(response.getBody(), RequestWrapper.RequestResponseHandler.class);
        Account ac= new Account();
        ac =[SELECT ID,name from account where Id=:acId];    //acId  passing in method:Not showned here
        ac.Name = result.Name;
        ac.enddate__c= result.endate;  //If end date is coming null, it shows null pointers exception  if(result.enddate!=null) assign the value,need to handle this logic for many fields

JSON Format:

  "enddate": "13JUN2021",
  "Name": "Company"
  • 2
    NB: The "ac" variable initialization is unnecessary and immediately generates garbage. Just assign it from the SOQL results. That said, if all you do is assign to all the fields from the result, then no SOQL query is needed at all, and all you need is new Account(Id = acId, Name = result.Name, ...);
    – Phil W
    Jun 13 '21 at 7:26
ac.enddate__c= result.enddate;

This can't be a null pointer exception, as result would need to be null, not endate. However, if you had something like:

ac.enddate__c = result.dates.enddate;

Then you could get a null pointer exception. The easy fix is to use the Safe Navigation Operator (?.) to avoid that exception:

ac.enddate__c = result.dates?.enddate;
  • I have added exact JSON Format in the question. I didnt get this Line : result.dates.enddate, whats 'dates' here? dates is dataType? Jun 13 '21 at 7:24
  • @Annappa It was an arbitrary example of a nested structure. If you only have a top-level object, you can't get a NullPointerException.
    – sfdcfox
    Jun 13 '21 at 7:31
  • okay got it. My bad,i have checked wrong debug.. thank you so much Jun 13 '21 at 7:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.