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?

2 Answers 2

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

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;
  }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .