The standard JSON pattern in Apex is serialize on the way out, deserialize into a strongly-typed class on the way in.
- Define the Apex class
Create a class with public fields matching the JSON shape: public class MyResponse { public String status; public List<MyItem> items; }.
- Serialize Apex to JSON
String jsonOut = JSON.serialize(myObject); Returns a JSON string ready for HTTP request bodies, debug logs, or storage.
- Deserialize JSON to Apex
MyResponse parsed = (MyResponse) JSON.deserialize(jsonString, MyResponse.class); Strongly-typed access to fields.
- Handle uncertain schemas
Map<String, Object> raw = (Map<String, Object>) JSON.deserializeUntyped(jsonString); Walk the Map for ad-hoc parsing.
- Handle null and missing fields
Apex deserializes missing fields to null. Check for null on every field access; assuming a field is present is the leading source of NullPointerExceptions.
- For large payloads, use JSON.JSONParser
Stream-parse via JSONParser to avoid building the full object tree in memory.
The strongly-typed class matching the JSON shape.
The standard methods for two-way conversion.
Required for any field that might be missing.
Required when the JSON exceeds the practical 6-MB heap limit.
- Apex JSON.deserialize requires field names in the Apex class to match the JSON. Mismatched names silently leave fields null; debug by logging the raw JSON before deserializing.
- Large JSON payloads consume CPU. The 10-second governor limit kicks in for naive deserializes of multi-megabyte payloads; switch to streaming parse.
- JSON does not enforce schema. Without JSON Schema validation, payload changes can break consumers silently; build contract tests for any production integration.
- JSON stored in Long Text Areas bypasses field-level security. Sensitive data should not be persisted as JSON in unmarked text fields.