I am creating a JSON generator that returns the created object to be parsed in a different method. However when I am creating a field using the writeStringField method of JSON with a value of null, it throws an error of null pointer exception.

JSONGenerator gen = JSON.createGenerator(true);
gen.writeStringField('ESignature', null); <----problem here (throws a Null Pointer Exception)


Is it not possible to create a Field with null value using JSON.createGenerator?


To write null type, you should use:



gen.writeNullField(String) ;

There is a separate method given. You can not write a String by saying it null https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_class_System_JsonGenerator.htm#apex_class_System_JsonGenerator


It may be the case that you want to write a string field but you are not sure that it has some value or its null.

It's always better to go with null check and then write a field.

public static String checkNullString(String sampleString) {
  String s ='';
  if(String.isBlank(sampleString)) {
    return s;
  } else {
    return sampleString;

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.