[SalesForce] JSON.createGenerator(true)

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?

Best Answer

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