How do Apex developers parse and map incoming JSON integration payloads into strongly typed objects?
Answer
Basics: Integrations send JSON strings. Apex needs typed objects to work with them safely. You define an Apex class (a wrapper) whose property names match the JSON keys, and JSON.deserialize fills it. Tools such as "JSON to Apex" generators help create the classes.
How it works:
- Define wrapper classes (inner classes are fine) with properties matching the JSON key names and types.
- Call
JSON.deserialize(body, OrderPayload.class); useList<OrderPayload>for arrays. - Unknown JSON keys are ignored by
deserialize;JSON.deserializeStrictthrows if a key is missing in the class. - For unpredictable structure use
Map<String,Object> m = (Map<String,Object>) JSON.deserializeUntyped(body);and cast as you navigate. - For huge documents use
JSONParserwithnextToken()and read values one at a time. - Convert wrapper data to sObjects in a bulk-safe loop, then DML once.
Advanced / deep dive: Trade-offs: typed wrappers give compile-time safety and readable code but break on reserved words used as keys (for example class, number, date names or hyphenated keys), where you pre-process with String.replace or use untyped parsing. Dates and datetimes parse only in ISO 8601 formats. Large payloads count toward heap (6 MB synchronous, 12 MB asynchronous); a streaming JSONParser or processing in Queueable/Batch reduces memory. Always wrap parsing in try/catch for JSONException and TypeException, and log the raw payload for support. For output use JSON.serialize (with option) or . Managed packages need to allow subscriber code to serialize or deserialize package classes.