Advanced 30 min read

JSON Serialization and Deserialization

By the end of this lesson, you'll be able to:

  • Convert an Apex object to a JSON string with JSON.serialize
  • Convert a JSON string back into an Apex object with JSON.deserialize
  • Explain why most modern integrations exchange data as JSON

Prerequisites: "Integration Basics: Sync vs Async"

Serializing: Apex to JSON

Map<String, Object> requestData = new Map<String, Object>{
    'accountName' => 'Riverbend Farms',
    'amount' => 5000
};

String jsonString = JSON.serialize(requestData);
System.debug(jsonString); // {"accountName":"Riverbend Farms","amount":5000}
  1. Map<String, Object> requestData = new Map<String, Object>{ — Module 16's Map, this time holding mixed-type values as Object.
  2. 'accountName' => 'Riverbend Farms', — a String value.
  3. 'amount' => 5000 — an Integer value, in the same map.
  4. }; — closes the map literal.
  5. (blank line)
  6. String jsonString = JSON.serialize(requestData); — converts the entire map into JSON text.
  7. System.debug(jsonString); // {"accountName":"Riverbend Farms","amount":5000} — the resulting JSON string.

JSON.serialize converts an Apex Map (Module 16), List, or custom class into its JSON text representation — exactly what a real HTTP callout's request body typically needs to contain.

Deserializing into a Map: flexible but untyped

String responseBody = '{"status":"success","rate":45.50}';
Map<String, Object> parsed = (Map<String, Object>) JSON.deserializeUntyped(responseBody);

Decimal rate = (Decimal) parsed.get('rate');
  1. String responseBody = '{"status":"success","rate":45.50}'; — raw JSON text, as if just returned from a callout.
  2. Map<String, Object> parsed = (Map<String, Object>) JSON.deserializeUntyped(responseBody); — parses it into a generic map — every value is typed Object until cast.
  3. (blank line)
  4. Decimal rate = (Decimal) parsed.get('rate'); — Module 18's casting, needed to use the value as a specific type.

JSON.deserializeUntyped parses JSON text into nested Map/List structures without needing a matching Apex class defined in advance — flexible, but every value needs an explicit cast (Module 18's polymorphism-adjacent casting) to use it as a specific type.

Deserializing into a typed class: safer, more direct

public class ShippingRateResponse {
    public String status;
    public Decimal rate;
}

String responseBody = '{"status":"success","rate":45.50}';
ShippingRateResponse parsed = (ShippingRateResponse) JSON.deserialize(responseBody, ShippingRateResponse.class);

System.debug(parsed.rate); // 45.50, already a Decimal, no casting needed
  1. public class ShippingRateResponse { — a plain class, shaped to match the JSON's fields.
  2. public String status; — matches the JSON's "status" key by name.
  3. public Decimal rate; — matches "rate".
  4. } — closes the class.
  5. (blank line)
  6. String responseBody = '{"status":"success","rate":45.50}'; — the same raw JSON.
  7. ShippingRateResponse parsed = (ShippingRateResponse) JSON.deserialize(responseBody, ShippingRateResponse.class); — JSON.deserialize, not deserializeUntyped, maps fields onto this specific class directly.
  8. (blank line)
  9. System.debug(parsed.rate); // 45.50, already a Decimal, no casting needed — the field is already the right type.

JSON.deserialize (not deserializeUntyped) maps JSON fields directly onto a matching Apex class's fields by name — this is Module 34's DTO/wrapper-class pattern in reverse: instead of Apex producing a shape for JSON to consume, JSON produces data mapped directly onto an Apex shape.

Exercise

Write a class OrderConfirmation with String orderId and Boolean confirmed fields, then deserialize '{"orderId":"ORD-1","confirmed":true}' into it.

Show hint

JSON.deserialize(jsonString, OrderConfirmation.class)

Salesforce: ○ Not connected Connect
APEX

Execution Results

Run your code to see the result.

JSON Serialization and Deserialization Quiz

1. What is the advantage of JSON.deserialize(json, MyClass.class) over JSON.deserializeUntyped(json)?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

JSON is the standard data format most external APIs speak — JSON.serialize and JSON.deserialize convert between Apex objects and JSON text, in both directions.