How do Apex JSONGenerator classes facilitate the programmatic construction of nested integration request bodies?
Answer
Basics: For most cases you define an Apex class mirroring the JSON and call JSON.serialize(obj). But sometimes the shape is dynamic, field names are Apex reserved words (class, date, number), or you must omit or rename fields conditionally. JSONGenerator lets you assemble the document manually and handles quoting and escaping.
How it works:
JSONGenerator gen = JSON.createGenerator(false);(true for pretty print).- Call
writeStartObject()/writeEndObject()andwriteStartArray()/writeEndArray()in matching pairs. - Add content with
writeStringField,writeNumberField,writeBooleanField,writeNullField,writeDateField,writeDateTimeField,writeObjectField, orwriteFieldNamefollowed by a value method. - Retrieve with
gen.getAsString()(after closing the root).
Advanced / deep dive: Use it when you need exact control, for example emitting a field only when not null, using vendor-specific names, or streaming large lists without building intermediate wrappers. writeObject / writeObjectField serialize an sObject or Apex object (nested) using standard serialization. Compared with alternatives: JSON.serialize(obj, true) is faster to write and easier to test but less flexible; JSON.serialize of Map<String,Object> handles dynamic keys too and is often simpler; rename keys with a wrapper that uses a different property name then replace the string, though this is hacky. The generator builds the string in heap, so mind size (6 MB sync / 12 MB async); for very large outputs, chunk the records and send several requests. Unit test the exact output string against an expected JSON, and use in the test to compare structure rather than raw text.