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}
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');
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
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)
JSON Serialization and Deserialization Quiz
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.