Whenever you need to send internal Salesforce data to an external application, a middleware tool like MuleSoft, or a front-end framework, that data must be translated into a universal format. In modern web development, that format is JSON. Converting database records into text strings is a fundamental task for any Salesforce developer.
JSON.serialize() method in Apex. This converts complex sObjects into standard JSON strings instantly.
Key Points Summary
- The native
JSON.serialize()method handles list and sObject conversions in a single line of code. - Serializing standard sObjects automatically injects Salesforce metadata (like the
attributesblock) into the payload. - To pass clean, lightweight data to non-Salesforce platforms, developers often use custom Apex Wrapper Classes.
- Date and DateTime fields are converted into standard ISO 8601 string formatting by default.
The Basic Implementation
To convert database records into JSON, you simply execute your SOQL query and pass the returned collection directly into the serialization method.
This Apex block queries five Account records and transforms them into a JSON text string:
// Execute a standard query and serialize the result
String query = 'SELECT Id, Name FROM Account LIMIT 5';
String jsonOutput = JSON.serialize(Database.query(query));
System.debug(jsonOutput);
Understanding the Resulting JSON Structure
When you serialize a standard sObject list, Salesforce automatically attaches metadata nodes to the payload. This helps internal systems recognize the object type and API endpoint path.
[
{
"attributes": {
"type": "Account",
"url": "/services/data/v66.0/sobjects/Account/001xxxxxxxxxxxx"
},
"Id": "001xxxxxxxxxxxx",
"Name": "Acme Corp"
}
]
Frequently Asked Questions (FAQ)
A: External third-party APIs often reject payloads containing Salesforce-specific metadata. To strip this out, map your sObject records into a custom Wrapper Class containing only the plain properties you need before passing the wrapper instance to JSON.serialize().
A: Yes, but by default, null values are included as null properties. If you want to keep your payloads minimal and skip null fields, use JSON.serialize(object, true) to enable pretty printing or use specialized serialization flags depending on your target system.
- Exceeding Heap Size: Serializing massive lists of sObjects with hundreds of fields can quickly exhaust your synchronous Apex heap limit. Always query only the fields you explicitly need.
- Foreign System Incompatibility: Sending raw sObjects with standard metadata to a strict REST API schema will cause parsing errors. Always review the receiving system's data contract first.
- Core Method:
JSON.serialize() - Input Format: sObjects, Lists, or custom Apex Wrapper Classes
- Output Format: Standard JSON string
- Best Practice: Use wrapper classes for external integrations to filter out internal metadata.