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.deserializematches the casing exactly. Use@JsonAccessor 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.
