Sub topic 7
Working with JSON payloads
This chapter covers how to turn Apex objects into JSON for a request body and turn a JSON response back into typed Apex. It assumes you can write Apex classes and methods, know what JSON looks like, and have already built a request and read a response status code in earlier chapters.
Why use typed classes
A callout body is plain text. You could build it by concatenating strings, but that breaks on quotes, line breaks, and null values. Apex gives you two safer routes:
JSON.serializeandJSON.deserializemap JSON to a typed Apex class.JSON.deserializeUntypedgives you a genericMap<String, Object>when the shape is not fixed.
Typed classes are the better default. The compiler checks field names, and the class documents the payload.
Serializing a request body
Define an inner class whose field names match the JSON keys. Then call JSON.serialize and pass the result to setBody.
public with sharing class TodoClient {
public class Todo {
public Integer id;
public Integer userId;
public String title;
public Boolean completed;
}
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 CalloutException('Create failed with status ' + res.getStatusCode());
}
return (Todo) JSON.deserialize(res.getBody(), Todo.class);
}
}The second argument to JSON.serialize is suppressApexObjects. When it is true, fields that are null are left out of the JSON. This matters here because a new todo has no id yet. With false, the body would contain "id":null, and some APIs reject that or treat it as an explicit value.
Set the Content-Type header yourself. Many services return 415 Unsupported Media Type or ignore the body when it is missing.
Deserializing a response
JSON.deserialize(jsonString, Todo.class) returns an Object, so cast it to your type. The call does the following:
- Keys in the JSON that match a field in the class are copied into it.
- Keys with no matching field are ignored.
- Fields with no matching key stay
null.
Because unknown keys are ignored, adding a field on the server side will not break your code. A misspelled field name in your class will fail silently, though, leaving that field null. Check the output once against a real response.
Handling lists and nested data
For a JSON array, pass a list type to deserialize:
List<TodoClient.Todo> todos =
(List<TodoClient.Todo>) JSON.deserialize(res.getBody(), List<TodoClient.Todo>.class);Nested objects work the same way. Add an inner class and use it as a field type.
Names that Apex cannot use
JSON keys such as class, date, or limit are reserved words in Apex, so you cannot name a field after them. You have two options:
- Rename the field in the class and then replace the key in the JSON string before deserializing, which is awkward and fragile.
- Use
JSON.deserializeUntypedand read the value from the map by key.
The second option is usually simpler for a handful of awkward keys.
Map<String, Object> parsed =
(Map<String, Object>) JSON.deserializeUntyped(res.getBody());
String title = (String) parsed.get('title');
Object limitValue = parsed.get('limit');Each value comes back as a generic Object. Numbers become Integer, Long, or Decimal, arrays become List<Object>, and nested objects become Map<String, Object>. You must cast at every level, so use this approach for small, irregular payloads.
Malformed JSON
If the body is not valid JSON, or a value cannot convert to the field type (for example a string where the class expects an Integer), deserialize throws a JSONException. A server under load may return an HTML error page with status 200 through a proxy, so wrap parsing when you cannot trust the source.
try {
return (TodoClient.Todo) JSON.deserialize(res.getBody(), TodoClient.Todo.class);
} catch (JSONException e) {
throw new CalloutException('Response was not valid JSON: ' + e.getMessage());
}The flow of a JSON call
Exercise
A POST to create a record fails because the server rejects "id":null in the body. What change to the JSON.serialize call fixes it, and why?
Show answer
Pass true as the second argument: JSON.serialize(newTodo, true). That suppresses null fields, so id is omitted from the body instead of being sent as null.
Exercise
A response contains the key limit, which you cannot use as an Apex field name. How can you still read its value?
Show answer
Parse the body with JSON.deserializeUntyped, cast the result to Map<String, Object>, and read the value with parsed.get('limit').