Sub topic 6
Returning and parsing JSON
This chapter covers how Apex REST turns Apex objects into JSON responses and JSON requests into Apex values. It assumes you can write a basic @RestResource class, know how RestContext works, and understand JSON structure. Status codes and error handling come in the next chapter.
Automatic serialization of return values
When a handler returns a value, the platform serializes it to JSON. This works for primitives, sObjects, lists, maps, and Apex classes whose members are global or public.
The response format follows the request's Accept header. It defaults to JSON when the client doesn't send one. You can override it by setting Content-Type on the RestResponse.
@RestResource(urlMapping='/v1/AccountSummary/*')
global with sharing class AccountSummaryService {
global class Summary {
global Id id;
global String name;
global Integer contactCount;
}
@HttpGet
global static Summary getSummary() {
String accountId = RestContext.request.requestURI.substringAfterLast('/');
Account a = [
SELECT Id, Name, (SELECT Id FROM Contacts)
FROM Account
WHERE Id = :accountId
WITH USER_MODE
LIMIT 1
];
Summary s = new Summary();
s.id = a.Id;
s.name = a.Name;
s.contactCount = a.Contacts.size();
return s;
}
}The response looks like this:
{"id":"001XXXXXXXXXXXXXXX","name":"Acme","contactCount":3}Returning a wrapper class instead of a raw sObject gives you control over the contract. An sObject return includes an attributes property and exposes your field API names, including __c suffixes. A wrapper lets you rename fields and hide internals.
Binding a JSON body to parameters
For @HttpPost, @HttpPut, and @HttpPatch, parameters that are not annotated are bound by name from the top-level properties of the JSON body. A body of {"name":"Acme","industry":"Energy"} binds to createAccount(String name, String industry). Missing properties become null.
Binding works for simple types. For nested or variable payloads, read the raw body and parse it yourself.
Parsing the raw body
RestContext.request.requestBody is a Blob. Convert it to a string, then deserialize.
global class OrderRequest {
global String customerId;
global List<Line> lines;
}
global class Line {
global String sku;
global Integer quantity;
}OrderRequest req = (OrderRequest) JSON.deserialize(
RestContext.request.requestBody.toString(),
OrderRequest.class
);JSON.deserialize throws a JSONException if the body is malformed or a value can't convert to the target type. Catch it and return a client error rather than letting it surface as a server failure.
By default, unknown properties in the JSON are ignored on deserialization by JSON.deserialize. If you want to reject unexpected input, use JSON.deserializeStrict, which throws on any property the class lacks.
When the shape is not fixed, use JSON.deserializeUntyped. It returns an Object that is a Map<String, Object> for objects and a List<Object> for arrays.
Map<String, Object> body = (Map<String, Object>)
JSON.deserializeUntyped(RestContext.request.requestBody.toString());
String type = (String) body.get('type');Controlling the output
To control output names or null handling, serialize yourself and write to the response.
Map<String, Object> payload = new Map<String, Object>{
'id' => 'A-100',
'note' => null
};
RestContext.response.addHeader('Content-Type', 'application/json');
RestContext.response.responseBody = Blob.valueOf(JSON.serialize(payload, true));Passing true as the second argument suppresses null values. Setting responseBody bypasses automatic serialization, so the handler should return void.
The following diagram shows both paths.
Common errors
| Symptom | Likely cause |
|---|---|
| Parameter is always `null` | JSON property name doesn't match the parameter name (matching is by name) |
| `JSONException` on valid-looking input | Type mismatch, such as a string where an `Integer` is expected |
| Response is not JSON | `Accept` header requests XML, or `Content-Type` was overridden |
| Extra `attributes` property in output | An sObject was returned directly |
Exercise
A client posts {"customerId":"C1","lines":[{"sku":"X","quantity":"two"}]} to a handler that calls JSON.deserialize into OrderRequest. What happens, and how should the handler respond?
Show answer
JSON.deserialize throws a JSONException because "two" can't convert to Integer. The handler should catch the exception and return a 400 status with a message, so the client sees a client error rather than a server error.
Exercise
You want a response that omits fields with null values. How do you do it, and what must the handler return?
Show answer
Build the payload, call JSON.serialize(payload, true), and assign the result to RestContext.response.responseBody as a Blob. The handler should return void, because a returned value is not needed once you set the body yourself.