Parsing JSON Responses
By the end of this lesson, you'll be able to:
- Parse a JSON response using JSON.deserializeUntyped
- Deserialize JSON directly into an Apex class with JSON.deserialize
Prerequisites: Making HTTP Callouts with HttpRequest
Untyped parsing: Map and List
Map<String, Object> data = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
Every JSON object becomes a Map<String, Object>, every array becomes a List<Object>, requiring casts to read nested values. Fast to write, but with no compile-time safety.
Typed parsing: deserialize into a class
Define an Apex class whose public fields match the JSON keys (case-sensitive by default), then:
MyResponseType result = (MyResponseType) JSON.deserialize(res.getBody(), MyResponseType.class);
Safer and more readable once the response shape is known in advance.
Deserializing into a typed class
public class WeatherResponse {
public Double tempCelsius;
public String conditions;
}
HttpResponse res = http.send(req);
WeatherResponse weather = (WeatherResponse) JSON.deserialize(res.getBody(), WeatherResponse.class);
System.debug(weather.tempCelsius);
The class's public field names must match the JSON's keys exactly (case-sensitive) — a mismatch leaves that field null rather than throwing an error.
Exercise
Given the JSON {"name":"Acme","employees":250}, write Apex using JSON.deserializeUntyped() to read the employees value into an Integer variable.
Show hint
Cast the deserialized result to Map<String, Object>, then cast the value you read out to Integer.
Parsing JSON Responses — Quick Check
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.deserializeUntyped() parses any JSON into nested Map/List structures for quick, loosely-typed access; JSON.deserialize() parses directly into a strongly-typed Apex class whose fields match the JSON's structure.