0

Im getting the error 'null argument for JSONGenerator.writeStringField()' when I call the below class from Visual Page.

Visualforce Page Code:

<apex:page standardController="Lead"   extensions="CreateSalesOrder" action="{!getRedir}">  
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection title="Error Messages" collapsible="false" columns="1">
  <apex:pageMessages id="errorMessages" />
  <apex:outputLink value="/{!$CurrentPage.parameters.id}">&lt; Return to Lead Page</apex:outputLink>
</apex:pageBlockSection>
 </apex:pageBlock>
  </apex:form>
</apex:page>

Below is the Apex Class

public with sharing class CreateSalesOrder {
private Boolean Failed = false;
private Integer responseCode;  
private String leadId;
public CreateSalesOrder(ApexPages.StandardController controller) {
Http h = new Http();
String url ='http://xxx.stage.com/salesforce/api';
this.leadId =  ApexPages.currentPage().getParameters().get('ID');
HttpRequest req = buildWebServiceRequest(url,  this.leadId);
HttpResponse res = invokeWebService(h,req);
System.Debug('RESPONSE: ' + res.getBody().trim());   
System.debug('HTTP Response Code: ' + res.getStatusCode());
System.debug('Response Body: ' + res.getBody());   
responseCode=res.getStatusCode();
if (res.getStatusCode()== 201){
    this.Failed =true;
}else{
    this.Failed =false;            
    } 
}    

public HttpRequest buildWebServiceRequest(String url, String ids) {
  //Build HTTP Request object
    JSONGenerator gen = JSON.createGenerator(true);    
    gen.writeStartObject();   

    List <Lead> Leads =  [SELECT Company,FirstName,LastName, Street, City, State, PostalCode, Phone, Email FROM Lead WHERE id=:Ids];
    for(Lead c:Leads){           
        gen.writeStringField('companyName', c.Company);
        gen.writeStringField('firstName',c.FirstName);
        gen.writeStringField('lastName',c.LastName);                
    }       
        gen.writeEndObject();        
        String jsonS = gen.getAsString();

        // Sending the http body with JSON 
            HttpRequest req = new HttpRequest();
            req.setEndpoint(url);
            req.setMethod('POST');
            req.setHeader('Content-Type', 'application/json;charset=UTF-8');
            req.setHeader('Accept', 'text/html');
            req.setbody(jsonS); 
            System.debug(req);
            return req;
}    

public HttpResponse invokeWebService(Http h, HttpRequest req) {
  //Invoke Web Service
   HttpResponse res = h.send(req); 
         return res;        
 }

public PageReference getRedir() {

if (!this.Failed) {
     ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Sorry.  We got ' + responseCode + ' ' + this.leadId +'  Response Code from atlas.  Please try again later.'));
  //PageReference newPage = new PageReference('http://www.google.com');
  //newPage.setRedirect(true);
  //return newPage;
  return null;
} else {
  PageReference newPage = new PageReference('http://xxx.stage.com/' + this.leadId);
  newPage.setRedirect(true);
  return newPage;
}
}
private final ApexPages.StandardController controller;
}

enter image description here

can you please let me what is the issue on above code?

0

You can't write a null value with the writeStringField function; instead, if the field is null, you have to use the writeNullField function.

That means your code needs to look more like:

Map<String, SobjectField> fieldMap = new Map<String, SobjectField> {
  'companyName' => Lead.Company, 'firstName' => Lead.FirstName, 
  'lastName' => Lead.LastName };
for(Lead c:Leads){
    for(String key: fieldMap.keyset()) {
        String value = (String)c.get(fieldMap.get(key));
        if(value == null) {
            gen.writeNullField(key);
        } else {
            gen.writeStringField(key, value);
        }
    }
}

Honestly, it'd be a lot easier to just write the code using a generic map instead:

String jsonS;
for(Lead c:Leads){
    jsonS = JSON.serialize(
        new Map<String, String> {
            'companyName' => c.Company,
            'firstName' => c.FirstName,
            'lastName' => c.LastName
         });
 }

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.