Sub topic 7
Working with JSON payloads
This chapter assumes you can already build and send a request with Http, HttpRequest and HttpResponse. It also assumes you can read a status code and a response body, and that you know basic Apex classes, collections and exceptions. Here we focus on the body: how to turn Apex data into JSON, and JSON back into Apex data, without surprises.
Why the JSON layer deserves attention
Most REST services send and receive JSON. Apex gives you three ways to work with it:
| Approach | Main classes | Best for |
|---|---|---|
| Typed (de)serialization | `JSON.serialize`, `JSON.deserialize` | Stable payloads you control or that have a documented schema |
| Untyped (de)serialization | `JSON.deserializeUntyped` | Variable shapes, or when you need only a few fields |
| Streaming | `JSONGenerator`, `JSONParser` | Very large payloads, or output that must match an exact layout |
Typed handling should be your default. The compiler checks field names and types, and the code documents the payload shape. The other two are tools for cases where a typed class does not fit.
Serializing Apex objects
JSON.serialize(obj) turns an object into a JSON string. Public member variables and properties become keys. The second overload, JSON.serialize(obj, true), suppresses null values, so unset fields are left out of the output instead of appearing as "field":null.
public class Todo {
public Integer id;
public Integer userId;
public String title;
public Boolean completed;
}
Todo t = new Todo();
t.userId = 1;
t.title = 'Write tests';
System.debug(JSON.serialize(t)); // {"completed":null,"title":"Write tests","userId":1,"id":null}
System.debug(JSON.serialize(t, true)); // {"title":"Write tests","userId":1}Two details matter here:
- Key order is not guaranteed. Do not compare serialized strings in tests. Deserialize them, or compare individual fields.
- Suppressing nulls changes meaning. Many APIs treat an omitted field as "leave unchanged" and an explicit
nullas "clear this value". Check the API's documentation before choosing.
Use JSON.serializePretty(obj) when you want readable output for debug logs. It adds whitespace, so do not send it unless the API requires it.
Type mappings worth remembering
Datetimeserializes as an ISO 8601 string such as2026-12-01T08:18:36.410Z.Dateserializes as2026-12-01.Decimal,Double,LongandIntegerall become JSON numbers.Idbecomes a string.Map<String, X>becomes a JSON object.List<X>andSet<X>become JSON arrays.sObjectrecords serialize with anattributeskey (typeandurl) in addition to their fields. If the external API rejects unknown keys, copy the data into a plain wrapper class first.
Deserializing into typed classes
JSON.deserialize(jsonString, Type) builds an object of the type you name. The type is a class literal such as Todo.class, and the result must be cast.
public with sharing class TodoReader {
public class Todo {
public Integer id;
public Integer userId;
public String title;
public Boolean completed;
}
public static Todo parseOne(String body) {
return (Todo) JSON.deserialize(body, Todo.class);
}
public static List<Todo> parseMany(String body) {
return (List<Todo>) JSON.deserialize(body, List<Todo>.class);
}
}The rules to know:
- Extra keys in the JSON are ignored. If the service adds a field tomorrow, your code keeps working. Use
JSON.deserializeStrictif you want an exception instead. - Missing keys leave the member as
null. A field absent from the JSON is indistinguishable from an explicitnull. Check fornullbefore you use a value. - Key matching is by name. The JSON key
userIdmust match the Apex memberuserId. Case matters on the JSON side to the extent that the names are compared as written, so mirror the API's spelling exactly. - Types must be compatible. A JSON string where Apex expects an
Integerthrows aSystem.JSONException. A number inside aStringmember is converted, but do not depend on that. - Arrays need a list type. Passing a JSON array to
Todo.classfails. UseList<Todo>.class.
Nested objects work the same way. Declare an inner class for each nested object, and use List<Inner> for arrays of objects. Apex needs the class to be defined before you rely on it in the type literal, so define the inner classes at the top of the wrapper.
Reserved words as JSON keys
Apex does not allow reserved words (such as class, long, number in some contexts, or end) as member names. If an API returns a key like "class", a typed class cannot represent it directly. There are two common workarounds:
public with sharing class ReservedWordDemo {
public class Course {
public String name;
public String class_x; // JSON key is "class"
}
public static Course parse(String body) {
// Rename the key before deserializing
String fixed = body.replace('"class":', '"class_x":');
return (Course) JSON.deserialize(fixed, Course.class);
}
}The string replace is simple but crude. It can also change matching text inside a string value. When the payload is complicated, use deserializeUntyped for the awkward part instead.
Untyped deserialization
JSON.deserializeUntyped returns an Object. Objects become Map<String, Object>, arrays become List<Object>, and scalars become String, Boolean, Integer, Long, Decimal or null. You must cast at each level.
public with sharing class UntypedDemo {
public static List<String> titles(String body) {
Map<String, Object> root = (Map<String, Object>) JSON.deserializeUntyped(body);
List<Object> items = (List<Object>) root.get('items');
List<String> result = new List<String>();
if (items == null) {
return result;
}
for (Object o : items) {
Map<String, Object> item = (Map<String, Object>) o;
result.add((String) item.get('title'));
}
return result;
}
}root.get('items') returns null when the key is missing, and casting null is safe. Iterating over null, however, throws a NullPointerException, so the guard above is needed. Casting a value of the wrong type, such as a number to String, throws a TypeException. For numbers, the exact runtime type depends on the value, so convert with Integer.valueOf(obj) or Decimal.valueOf(String.valueOf(obj)) instead of casting.
Untyped parsing is flexible but verbose, and typos in key names become runtime null values instead of compile errors. Reach for it when the shape varies, not as a shortcut.
Streaming with JSONGenerator and JSONParser
JSONGenerator writes JSON piece by piece. Use it when a payload needs a layout that a class cannot express, such as a key that is a reserved word, or conditional fields.
public with sharing class GeneratorDemo {
public static String buildBody(String title, Boolean includeFlag) {
JSONGenerator gen = JSON.createGenerator(false);
gen.writeStartObject();
gen.writeStringField('title', title);
gen.writeStringField('class', 'task'); // reserved word is fine as a string
if (includeFlag) {
gen.writeBooleanField('completed', false);
}
gen.writeEndObject();
return gen.getAsString();
}
}JSONParser reads tokens one at a time (parser.nextToken(), parser.getText()). It uses less memory than building a full object tree, which helps when a response is close to the heap limit. It is also more code to write and to get wrong, so use it only when memory or structure forces your hand.
Putting JSON handling inside the callout
Keep serialization and parsing in one place, next to the status check, and turn parsing failures into a predictable exception. A payload that arrives with status 200 can still be malformed or have the wrong shape.
public with sharing class TodoApi {
public class Todo {
public Integer id;
public Integer userId;
public String title;
public Boolean completed;
}
public class TodoApiException extends Exception {}
public static Todo create(Todo newTodo) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Todo_API/todos');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(newTodo, true));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 201) {
throw new TodoApiException('Create failed: ' + res.getStatusCode());
}
try {
return (Todo) JSON.deserialize(res.getBody(), Todo.class);
} catch (JSONException e) {
throw new TodoApiException('Unreadable response body: ' + e.getMessage());
}
}
}The order matters. Check the status code first, because an error response often has a different JSON shape (for example {"error":"..."}) that would fail or half-fill the typed class. Only then parse the body.
Common errors
System.JSONException: Malformed JSONorUnexpected character. The body is not JSON. This often means the service returned an HTML error page or an empty body. Check the status code and theContent-Typeheader first.Illegal value for primitiveorCannot deserialize instance of ... from VALUE_STRING. A value's JSON type does not match the member's Apex type. Change the member type, or parse that field untyped.TypeException: Invalid conversion from runtime type .... You cast an untyped value to the wrong type, for example aList<Object>to aMap. PrintString.valueOf(obj)to see what you actually received.- A field is silently
null. The JSON key does not match the Apex member name, or the key is absent. Becausedeserializeignores unknown keys, typos here do not raise errors. Compare the raw body with your class. System.LimitException: Apex heap size too large. The body, the string, and the object tree all sit in memory at once. Request fewer records, use pagination, or switch toJSONParser.
Exercise
A service returns [{"id":1,"title":"A","priority":"high"},{"id":2,"title":"B"}]. Your class Todo has members Integer id, String title and Integer priority. What happens when you call JSON.deserialize(body, List<Todo>.class), and what would you change?
Show answer
The call throws a JSONException, because "high" is a string and the member priority is an Integer. The second record is fine on its own, since its missing priority simply stays null. The fix is to change the member to String priority to match the real data. If the field can hold different types, read it with JSON.deserializeUntyped instead.
Exercise
Why should you check res.getStatusCode() before calling JSON.deserialize on the body?
Show answer
Error responses usually have a different JSON shape or are not JSON at all. Deserializing them into your success class either throws a JSONException or produces an object with mostly null fields, and both hide the real problem. Checking the status first lets you report the actual failure.