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.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 {
  if (response.getStatusCode() == 200) {
} else {
System.debug('Callout failed: ' + response);

1 Answer 1


Use JSON.serialize to automatically format the body:

        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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .