How can I use “json.serialize” in Apex for converting a list format into JSON?
I am currently working on a specific project that is related to sending day from a custom object called “Employee_ _C” to an external system via a REST API callout. Explain to me how can I use “json.serialize” in Apex for converting a list of employees' records into the format of JSON before sending it over the REST API.
In the context of Salesforce, you can convert a list of “employee_ _ C” records into the format of JSON by using “json.serialize” apex for sending over a REST API callout by using the steps which are given below:-
// Step 1: Query the Employee__c records
List employees = [SELECT Id, Name, Email FROM Employee__c LIMIT 100];
// Step 2: Convert the list of Employee__c records to a JSON string
String jsonPayload = JSON.serialize(employees);
// Step 3: Make the REST API callout and include the JSON payload in the request body
HttpRequest request = new HttpRequest();
Request.setEndpoint(‘https://api.example.com/employees’);
Request.setMethod(‘POST’);
Request.setHeader(‘Content-Type’, ‘application/json’);
Request.setBody(jsonPayload);
// Step 4: Send the request
Http http = new Http();
HttpResponse response = http.send(request);
// Step 5: Handle the response as needed
If (response.getStatusCode() == 200) {
// Success handling
} else {
// Error handling
}