0

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);
  } 
}
}

1 Answer 1

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.