Intermediate 15 min read

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.

APEX

Parsing JSON Responses — Quick Check

1. What Apex type does a JSON object become when parsed with JSON.deserializeUntyped()?

2. JSON.deserialize() requires the target Apex class's field names to match the JSON keys.

3. What's the main advantage of JSON.deserialize() over deserializeUntyped()?

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.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.