2

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.

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


Question:

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

5

To write null type, you should use:

gen.writeNull();

or

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

| improve this answer | |
1

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;
  }
}
| improve this answer | |

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.