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.

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