# How do Apex JSONGenerator classes facilitate the programmatic construction of nested integration request bodies?

**Topic:** Integration · **Difficulty:** Medium · **Tags:** Integration, JSONGenerator, Payload Serialization

Read it on the site: https://www.forcechallenges.com/interview-questions/how-do-apex-jsongenerator-classes-facilitate-the-programmatic-construction-of-nested-integration-request

## 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:**
1. `JSONGenerator gen = JSON.createGenerator(false);` (true for pretty print).
2. Call `writeStartObject()` / `writeEndObject()` and `writeStartArray()` / `writeEndArray()` in matching pairs.
3. Add content with `writeStringField`, `writeNumberField`, `writeBooleanField`, `writeNullField`, `writeDateField`, `writeDateTimeField`, `writeObjectField`, or `writeFieldName` followed by a value method.
4. 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 `JSON.deserializeUntyped` in the test to compare structure rather than raw text.

**Code / config example:**
```apex
public static String buildOrders(List<Order> orders) {
    JSONGenerator gen = JSON.createGenerator(false);
    gen.writeStartObject();
    gen.writeStringField('source', 'salesforce');
    gen.writeFieldName('orders');
    gen.writeStartArray();
    for (Order o : orders) {                       // no SOQL or DML inside the loop
        gen.writeStartObject();
        gen.writeStringField('id', o.Id);
        gen.writeNumberField('total', o.TotalAmount == null ? 0 : o.TotalAmount);
        gen.writeDateField('date', o.EffectiveDate);
        gen.writeEndObject();
    }
    gen.writeEndArray();
    gen.writeEndObject();
    return gen.getAsString();
}
```

**Hidden gotchas & must-remember points:**
- Unbalanced start/end calls throw a `JSONException`.
- `writeNumberField` does not accept null values; handle nulls yourself.
- Dates and datetimes are written in ISO format; check what the target expects.
- `getAsString()` should be called after the root is closed.
- Pretty print adds size; use compact output on the wire.

**Best practice:** Prefer typed wrapper classes for fixed contracts and reach for `JSONGenerator` only when dynamic control is required.

---
Source: ForceChallenges · last updated 2026-11-02
