Salesforce Asked by Luke Higgins on November 8, 2021
The external site that I’m trying to send Salesforce data to, requires that all dates/datetimes must be in ISO 8601 format. I am curious about how to accomplish this within my Apex class. The field Training_Class_Start_Date__c is the one that needs to be converted.
Apex class:
global class apiCallout {
@future (callout=true)
public static void makePostUpdatePlacement(String icid) {
Internal_Candidate__c intCan = [SELECT id, Status__c, Name, H_Update__c, Training_Class_Start_Date__c FROM Internal_Candidate__c WHERE id=:icid];
Http http = new Http();
HttpRequest request = new HttpRequest();
HttpResponse response = new HttpResponse();
request.setEndpoint('https://api.secretkey.com');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json;charset=UTF-8');
if(intCan.H_Update__c == 'Training Class Start' && intCan.Training_Class_Start_Date__c != null){
request.setBody('{"PlacementId":"'+intCan.Name+'","CandidateId": "'+intCan.Id+'","OwnerId": 000001,"StartDate":"'+intCan.Training_Class_Start_Date__c+'","Status": "Internal","JobTitle": "Internal Candidate","Company": "Company"}');
}
response = http.send(request);
if (response.getStatusCode() != 201) {
System.debug('The status code returned was not expected: ' +
response.getStatusCode() + ' ' + response.getStatus());
} else {
System.debug(response.getBody());
}
if (response.getStatusCode() == 200) {
} else {
System.debug('Callout failed: ' + response);
}
}
}
Use JSON.serialize to automatically format the body:
request.setBody(
JSON.serialize(
new Map<String, Object> {
'PlacementId' => intCan.Name,
'CandidateId' => intCan.Id,
'OwnerId' => '000001',
'StartDate' => intCan.Training_Class_Start_Date__c,
'Status' => 'Internal',
'JobTitle' => 'Internal Candidate',
'Company' => 'Company'
}
)
);
This will also automatically escape quotes and other special characters that JSON may have trouble with.
As a general rule, you should "never" (as in, consider it a last resort) try to encode JSON by hand, but instead use a library call (such as JSON.serialize) to make sure that everything is encoded correctly.
Answered by sfdcfox on November 8, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP