Salesforce Dictionary - Free Salesforce GlossarySalesforce Dictionary
Full JSON (JavaScript Object Notation) entry
How-to guide

Work with JSON in Apex

The standard JSON pattern in Apex is serialize on the way out, deserialize into a strongly-typed class on the way in.

By Dipojjal Chakrabarti · Founder & Editor, Salesforce DictionaryLast updated May 21, 2026

The standard JSON pattern in Apex is serialize on the way out, deserialize into a strongly-typed class on the way in.

  1. Define the Apex class

    Create a class with public fields matching the JSON shape: public class MyResponse { public String status; public List<MyItem> items; }.

  2. Serialize Apex to JSON

    String jsonOut = JSON.serialize(myObject); Returns a JSON string ready for HTTP request bodies, debug logs, or storage.

  3. Deserialize JSON to Apex

    MyResponse parsed = (MyResponse) JSON.deserialize(jsonString, MyResponse.class); Strongly-typed access to fields.

  4. Handle uncertain schemas

    Map<String, Object> raw = (Map<String, Object>) JSON.deserializeUntyped(jsonString); Walk the Map for ad-hoc parsing.

  5. 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.

  6. For large payloads, use JSON.JSONParser

    Stream-parse via JSONParser to avoid building the full object tree in memory.

Mandatory fields
Apex class definitionrequired

The strongly-typed class matching the JSON shape.

JSON.serialize / JSON.deserializerequired

The standard methods for two-way conversion.

Field-level null handlingrequired

Required for any field that might be missing.

Streaming JSONParser (large payloads)required

Required when the JSON exceeds the practical 6-MB heap limit.

Gotchas
  • 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.

See the full JSON (JavaScript Object Notation) entry

JSON (JavaScript Object Notation) includes the definition, worked example, deep dive, related terms, and a quiz.