Salesforce Dictionary - Free Salesforce GlossarySalesforce Dictionary
Salesforce Developer
easy

How do you serialize and deserialize JSON in Apex?

Apex provides the JSON class for converting between Apex objects and JSON strings.

Serialize: `apex Account a = new Account(Name='Acme', Industry='Tech'); String jsonStr = JSON.serialize(a); // {"attributes":{"type":"Account"},"Name":"Acme","Industry":"Tech"}

String pretty = JSON.serializePretty(a); // human-readable `

Deserialize: `apex String json = '{"name":"Acme","industry":"Tech"}';

// Type-safe — needs a class with matching fields public class AccountDto { public String name; public String industry; } AccountDto dto = (AccountDto) JSON.deserialize(json, AccountDto.class);

// Untyped — returns Object/Map for flexibility Object parsed = JSON.deserializeUntyped(json); Map<String,Object> m = (Map<String,Object>) parsed; String name = (String) m.get('name'); `

Important nuances:

  • Field names are case-sensitive for type-safe deserialization. JSON.deserialize matches the casing exactly. Use @JsonAccess or transform the JSON if external systems use different casing.
  • `JSON.deserializeStrict` fails if JSON has fields not in the class (catches typos).
  • `JSON.serialize` includes nulls by default. Use JSON.serialize(obj, true) to suppress nulls.
  • Lists, Maps, nested objects all serialize naturally.
  • DateTime serializes as ISO 8601 string.

Common use cases: REST callouts (request body, response parsing), Platform Event payloads, custom serialization for archival.

Why this answer works

Foundational. Mentioning case-sensitivity, deserializeStrict, and the suppress-nulls option signals real integration coding.

Follow-ups to expect

Related dictionary terms