How can string apex being truncated?

241    Asked by DavidPiper in Salesforce , Asked on Mar 3, 2023

I am passing a string that holds the message to be sent to our endpoint from a trigger to a class and it seems if the string is over 270 characters it truncates the field. I have not been able to find any information relating to a size limit - but if I remove a few of the build statements, then the end of the string is correct.

Can anyone tell me why this happens and what I should do to correct it?

The debug values of the field buildMessage is as follows:

value in trigger:

Message before is :{"accountid": "9999999999cu5SXQAY", "title":"Kal", "physician_c": 5640, "market_rep_c":Barry", "email":"null", "phone":"null", "mobilephone":"null", "fax":"null", "mailingstreet":"null", "mailingcity":"null", "mailingpostalcode":"null", "mailingcountry":"
value in class
Message after is :{"accountid": "9999999999cu5SXQAY", "title":"Kal", "physician_c": 5640, "market_rep_c":Barry", "email":"null", "phone":"null", "mobilephone":"null", "fax":"null", "mailingstreet":"null", "mailingcity":"null", "mailingpostalcode":"null", "mailingcountry":"
The trigger code:
trigger ConOut on Contact (after update) {
  String buildMessage;
    for(Contact a:Trigger.new){
        buildMessage = '{';    
        buildMessage = buildMessage + '"accountid": "' + a.accountid + '"'; 
        buildMessage = buildMessage + ', "title":' + '"' + a.title + '"';
        buildMessage = buildMessage + '"physician_c":' + a.physician__c;
        buildMessage = buildMessage + ', "market_rep_c":' + a.market_rep__c + '"';   
        buildMessage = buildMessage + ', "email":' + '"' + a.email + '"';        
        buildMessage = buildMessage + ', "phone":' + '"' + a.phone + '"';  
        buildMessage = buildMessage + ', "mobilephone":' + '"' + a.mobilephone + '"';   
        buildMessage = buildMessage + ', "fax":' + '"' + a.fax + '"';   
        buildMessage = buildMessage + ', "mailingstreet":' + '"' + a.mailingstreet + '"';      
        buildMessage = buildMessage + ', "mailingcity":' + '"' + a.mailingcity + '"'; 
        buildMessage = buildMessage + ', "mailingpostalcode":' + '"' + a.mailingpostalcode + '"';
        buildMessage = buildMessage + ', "mailingcountry":' + '"' + a.mailingcountry + '"';         
        buildMessage = buildMessage + '}';
        system.debug('Message before is :' + buildMessage);
        OurCallout4.putContact(buildMessage);  
    }
}

The class code:

public class OurCallout4 {
    public static String generatedToken {set; get;}
    static String errorMessage {set; get;}
    static String TimelineResponse {set; get;}
    
    @future(callout = true)
    
    public static void putContact(string buildMessage) {    
        HttpRequest req = new HttpRequest();
        req.setMethod('POST');
        req.setHeader('Authorization', 'Basic ' + EncodingUtil.base64Encode(Blob.valueOf('hardcoded_client_id' + ':' + 'hardcoded_client_key')));
        req.setHeader('content-type', 'application/x-www-form-urlencoded');
        req.setEndpoint('https://ourdomain.com/token');
        req.setBody('grant_type=client_credentials');
        Http http = new Http();
        HTTPResponse res = http.send(req);
        JSONParser objParse = JSON.createParser(res.getBody());
        while (objParse.nextToken() != null) 
        {
           if (objParse.getCurrentToken() == JSONToken.FIELD_NAME && objParse.getText() == 'access_token')
           {                               
              objParse.nextToken();
              generatedToken = objParse.getText();
           }
        }
            if(generatedToken == null ) 
            {
                TimelineResponse = 'Error while generating token, so unable to get messages. Check your debug log.';
                return;
            }
            HttpRequest objReq = new HttpRequest();
            objReq.setEndpoint('https://ourdomain.com/ourendpoint');
            objReq.setMethod('POST');
            objReq.setHeader('Authorization', 'Bearer ' + generatedToken);
            
            objReq.setBody(buildMessage);
        system.debug('Message after is :' + buildMessage);
            Http objHttp = new Http();
            HTTPResponse objRes = objHttp.send(objReq);
            TimelineResponse = objRes.getBody();
            if(String.isBlank(TimelineResponse))
            {
               TimelineResponse = objRes.toString();
            }
    }
}
Answered by Claudine Tippins

Your string apexis not actually truncated. What you're seeing is simply an artifact of using system.debug();. A similar thing happens when you debug lists and maps. If you open the raw log in the developer console (logs tab, right click the target log, select "open raw log"), you'll see the entire string.

On a secondary note, the method you're using to build your JSON is pretty obtuse. You could instead build a Map and pass it to JSON.serialize().
// Pseudocode
for( contacts ){
    Map data = new Map{
        'field 1' => contact.field1,
        'field 2' => contact.field2,
        //... etc
        'last field' => contact.LastField
    };
    system.debug(JSON.serialize(data));
}
// If having invalid identifiers (i.e. double underscores in your JSON string)
// isn't a dealbreaker, you could also save some typing by using
// getPopulatedFieldsAsMap()
Set targetFields = new Set{ 'field1', 'field2', ... , 'last field'};
for( Contact){
    // cloning the resulting map allows us to make changes to it (otherwise
    // it's immutable)
    Map populatedFields = contact.getPopulatedFieldsAsMap().clone();
    // keySet() retrieves the set of keys for the map (no surprise)
    // retainAll() retains all of the values that are present in the set passed
    // as an argument
    // The magic is that by operating on the map's keyset, removing keys also
    // removes data from the map
    populatedFields.keySet().retainAll(targetFields);
    system.debug(JSON.serialize(populatedFields));
}


Your Answer

Interviews

Parent Categories