Sub topic 6
Returning and parsing JSON
This chapter covers how Apex REST turns Apex values into JSON responses and JSON requests into Apex values. It assumes you can already write a @RestResource class with @HttpGet and @HttpPost methods, and that you know RestContext.request and RestContext.response. It also assumes you are comfortable with JSON objects, arrays and data types.
Two ways to produce a response
Apex REST gives you two ways to write a response body.
- Automatic. Your handler method returns a value, and the platform serializes it to JSON.
- Manual. Your handler method is
void. You serialize the data yourself and assign aBlobtoRestContext.response.responseBody.
The automatic approach is shorter. The manual approach gives you control over null handling, headers and error bodies.
Automatic serialization
A non-void handler can return any of these types:
| Return type | JSON produced |
|---|---|
| Primitive (`String`, `Integer`, `Boolean`, `Decimal`) | A JSON scalar |
| `Date`, `Datetime` | An ISO 8601 string, such as `"2026-12-01"` or `"2026-12-01T11:41:58.478Z"` |
| `Id` | A string |
| `Blob` | Handled differently from other types (see the warning below) |
| sObject | An object with an `attributes` entry plus the queried fields |
| `List<T>`, `Set<T>` | An array |
| `Map<String, T>` | An object |
| Class instance | An object with one key per member variable or property |
When you return an sObject, only the fields you queried or assigned appear. The result also contains an attributes object holding the sObject type and a record URL. Clients that bind JSON to strict models often choke on it. If you want a stable contract, return your own class instead of the sObject.
Wrapper classes
A wrapper class (a data transfer object) separates your API shape from your schema. Renaming a custom field then does not break clients. Keep these rules in mind:
- Member variables and properties with getters and setters are serialized.
- Methods are not serialized.
- Members marked
transientare skipped. - Declare the class
globalwhen it is exposed through aglobalhandler, as the examples in this tutorial do.
Serializing manually
The manual style makes the status code, header and body explicit. This helper is used in the full example below:
private static void writeJson(Integer status, Object payload) {
RestResponse res = RestContext.response;
res.statusCode = status;
res.addHeader('Content-Type', 'application/json');
res.responseBody = Blob.valueOf(JSON.serialize(payload, true));
}The second argument to JSON.serialize is suppressApexObjectNulls. When it is true, null members of your classes are left out of the output. Without it, every null member is written as "field": null. Leaving nulls out keeps responses small. A client that distinguishes "absent" from "null" must know which convention you chose. Note that the flag applies to Apex object members, not to nulls inside a Map.
JSON.serializePretty adds indentation. It is useful when debugging in logs and wasteful in production.
Parsing request JSON
There are three ways to read the body, from most to least structured.
Parameter binding
For @HttpPost, @HttpPut and @HttpPatch, the platform matches top-level JSON keys to method parameter names, as in the earlier createAccount(String name, String industry) example. This works for flat bodies. It breaks down when the body is nested, when you want to validate before binding, or when you need to control the error response for bad input.
Typed deserialization
Read the body as a string and call JSON.deserialize with a target type. Key names in the JSON must match member names in your class. Matching is case-sensitive. A key that the class lacks is ignored by JSON.deserialize. Use JSON.deserializeStrict when unknown keys should be an error.
Untyped deserialization
JSON.deserializeUntyped returns nested Map<String, Object> and List<Object> structures. Use it when the shape varies, or when a key is not a legal Apex identifier. A key such as limit or order-id cannot be a member name, so you cannot bind it to a class.
String body = '{"accountId":"001000000000001AAA","lines":[{"sku":"A1","quantity":2}]}';
Map<String, Object> root = (Map<String, Object>) JSON.deserializeUntyped(body);
List<Object> lines = (List<Object>) root.get('lines');
Map<String, Object> first = (Map<String, Object>) lines[0];
Integer qty = Integer.valueOf(String.valueOf(first.get('quantity')));
System.debug(first.get('sku') + ' x ' + qty);Every nested value needs a cast. Do not assume which numeric type a number arrives as, because it depends on the value. Converting through String.valueOf first, as above, is safe for either case.
A complete handler
This service accepts an order as JSON, validates it, and answers with JSON in every case, including failures. It stays within what this chapter covers. Status codes and error handling are covered in more depth in the next chapter.
@RestResource(urlMapping='/v1/Orders/*')
global with sharing class OrderRestService {
global class Line {
global String sku;
global Integer quantity;
}
global class OrderRequest {
global String accountId;
global Date requestedDate;
global List<Line> lines;
}
global class OrderResponse {
global String status;
global Integer lineCount;
global String message;
}
@HttpPost
global static void createOrder() {
OrderResponse reply = new OrderResponse();
RestRequest req = RestContext.request;
if (req.requestBody == null || req.requestBody.size() == 0) {
reply.status = 'error';
reply.message = 'Request body is required.';
writeJson(400, reply);
return;
}
try {
OrderRequest payload = (OrderRequest) JSON.deserialize(
req.requestBody.toString(), OrderRequest.class);
if (payload.lines == null || payload.lines.isEmpty()) {
reply.status = 'error';
reply.message = 'At least one line is required.';
writeJson(400, reply);
return;
}
reply.status = 'accepted';
reply.lineCount = payload.lines.size();
writeJson(201, reply);
} catch (JSONException e) {
reply.status = 'error';
reply.message = 'Invalid JSON: ' + e.getMessage();
writeJson(400, reply);
}
}
private static void writeJson(Integer status, Object payload) {
RestResponse res = RestContext.response;
res.statusCode = status;
res.addHeader('Content-Type', 'application/json');
res.responseBody = Blob.valueOf(JSON.serialize(payload, true));
}
}Three details matter here:
- The empty-body check comes first. Calling
toString()on a nullrequestBodythrows aNullPointerException, which the client sees as a generic 500. JSON.deserializethrowsJSONExceptionboth for malformed JSON and for values that do not fit the target type, such as a non-date string in aDatemember. One catch block handles both.- The
Datemember shows why client formats matter. It accepts"2026-12-01"and rejects"12/01/2026".
A test can verify the output by parsing the response body, without making an HTTP call:
@IsTest
private class OrderRestServiceTest {
@IsTest
static void createOrderAcceptsValidJson() {
RestRequest req = new RestRequest();
req.requestURI = '/services/apexrest/v1/Orders';
req.httpMethod = 'POST';
req.requestBody = Blob.valueOf(
'{"accountId":"001000000000001AAA","requestedDate":"2026-12-01",'
+ '"lines":[{"sku":"A1","quantity":2}]}');
RestContext.request = req;
RestContext.response = new RestResponse();
OrderRestService.createOrder();
Assert.areEqual(201, RestContext.response.statusCode);
Map<String, Object> body = (Map<String, Object>)
JSON.deserializeUntyped(RestContext.response.responseBody.toString());
Assert.areEqual('accepted', body.get('status'));
Assert.areEqual(1, Integer.valueOf(String.valueOf(body.get('lineCount'))));
}
@IsTest
static void createOrderRejectsMalformedJson() {
RestRequest req = new RestRequest();
req.requestURI = '/services/apexrest/v1/Orders';
req.httpMethod = 'POST';
req.requestBody = Blob.valueOf('{"lines": [');
RestContext.request = req;
RestContext.response = new RestResponse();
OrderRestService.createOrder();
Assert.areEqual(400, RestContext.response.statusCode);
}
}Edge cases and gotchas
- Request format. Apex REST supports JSON and XML. Send
Content-Type: application/jsonandAccept: application/jsonfrom clients so the format is never ambiguous. - Missing versus null. After
JSON.deserialize, a key that was absent and a key set tonullboth leave the member null. If the difference matters, as in a PATCH that should clear a field, usedeserializeUntypedand checkcontainsKey. - Large numbers and decimals. Use
Decimalfor money. ADoublemember can introduce rounding artifacts. - Polymorphic lists. A
List<Object>member in a class is deserialized as untyped values. If you need typed elements, declare a typed list or parse that part separately. - Heap size. Serialization and deserialization hold the whole document in memory. Very large payloads count against the heap limit, so cap the number of records you accept or return.
Exercises
Exercise
A handler returns an Account sObject that you queried with SELECT Id, Name FROM Account. The client complains about an unexpected attributes key. What are two ways to remove it from the response?
Show answer
Return a wrapper class with only the members you want, populated from the Account. Alternatively, build a Map<String, Object> containing only the keys you want and return or serialize that. Either way the sObject's attributes entry is not produced.
Exercise
A client sends the body {"accountId":"001000000000001AAA","extra":true} to a handler that calls JSON.deserialize into a class with only an accountId member. Does the call throw? What changes if you use JSON.deserializeStrict?
Show answer
JSON.deserialize does not throw. It ignores the unknown extra key. JSON.deserializeStrict throws a JSONException because the class has no matching member.
Exercise
Why should a handler check that RestContext.request.requestBody is not null before calling toString() on it, and what status code fits an empty body?
Show answer
A request with no body leaves requestBody null, so calling toString() throws a NullPointerException that reaches the client as a generic 500. Checking first lets you return 400 with a clear message.