Showing posts with label control characters. Show all posts
Showing posts with label control characters. Show all posts

Saturday, 13 September 2014

JSON Integration and handling control characters in JSON Response

Below is the code which sends a Post Http Request and handles the Special or Control characters in Json response while parsing.

String jsonStr = '';
String url = 'https://www.xyz.com/test.cfm'; //Endpoint url
String username = '<Username>';
String password = '<Password>';
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setEndpoint(url);
req.setHeader('Content-type', 'application/json;charset=UTF-8');
Blob headerValue = Blob.valueOf(username + ':' + password);
String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
req.setHeader('Authorization', authorizationHeader);
Http http = new Http();
HTTPResponse res = http.send(req);
jsonStr = res.getBody();
//Replace the control characters with space
jsonStr = jsonStr.replaceAll('\\p{Cntrl}', '');
JSONParser parser = JSON.createParser(newJsonStr);
while (parser.nextToken() != null) {
// Start at the array of invoices.
if (parser.getCurrentToken() == JSONToken.START_ARRAY) {
while (parser.nextToken() != null) {
if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
<Your Parser logic>
}
}
}
}

Note:- While using the regex '\\p{Cntrl}' , if the length of the Json response is more than the limit then you may get Regex too complicated Error message in apex class. In this case you can apply regex on substring of a Json string and then join the substring back as shown below:-

Integer jsonlength = jsonStr.length();
    String newJsonstr = '';
    
    
    if(jsonlength > 100000)
    {
      Integer Quot = jsonlength/100000;
      Integer modcheck = math.mod(jsonlength,100000);
      
        
        for(Integer i = 0; i < Quot; i++)
           newJsonStr += jsonStr.substring(i * 100000,100000 * (i+1)).replaceAll('\\p{Cntrl}', '');
    
    if(modcheck > 0)
       newJsonStr += jsonStr.substring(jsonlength - modcheck,jsonlength).replaceAll('\\p{Cntrl}', '');
      
    }