[SalesForce] Deserialize json request error – unexpected character

I am getting this error when trying to deserialize an HTTP response – hope you can help:

FATAL_ERROR System.JSONException: Unexpected character ('<' (code
60)): expected a valid value (number, String, array, object, 'true',
'false' or 'null') at input location [2,2]

Very quickly, I am doing a POC on connecting two Salesforce orgs via REST. I have created a super simple REST service in a sandbox and am now trying to call it from a different sandbox. I am able to connect, but how do I deserialize the response get – the access token – and call my REST service?

This is my code – I just call it through execute anonymous for now:
String accessToken;
String sfdcInstanceURL;

try{
    HttpRequest req = new HttpRequest();
    req.setEndpoint(ENP_POINT_URL);
    req.setMethod('POST');
    Blob headerValue = Blob.valueOf(USERNAME + ':' + PASSWORD);
    String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
    req.setHeader('Authorization', authorizationHeader);
    req.setHeader('Accept','application/json');
    req.setBody(String.format(REQUEST_BODY ,new string[]{CONSUMER_KEY,CONSUMER_SECRET,
                                                         USERNAME,PASSWORD}));
    req.setTimeout(60000);
    Http http = new Http();
    HttpResponse hRes = http.send(req);

    Map<String, String> results = (Map<String, String>) JSON.deserializeUntyped(hRes.getBody());
    //Map<String,String> res = (Map<String,String>) JSON.deserialize(hRes.getBody(),Map<String,String>.class);

    accessToken = results.get('oauth_token');
    sfdcInstanceURL = results.get('loginURL');

    System.debug('Response1: ' + hres.getBody());
    System.debug('Response1: ' + hres);

    System.debug('accessToken: ' + accessToken);
    System.debug('sfdcInstanceURL: ' + sfdcInstanceURL);

    req = new HttpRequest();
    req.setEndpoint(ENP_POINT_URL2);
    req.setMethod('POST');
    req.setHeader('Content-Type', 'application/json;charset=UTF-8');
    req.setBody('{"name":"mighty moose"}');

    //System.debug('Response3: ' + res.getBody());
    //System.debug('Response3: ' + res);     

    //OAuth objAuthenticationInfo = (OAuth)JSON.deserialize(res.getbody(), OAuth.class);
    //return objAuthenticationInfo;
}catch(CallOutException ce){
    throw ce;
}

This is the response body:
enter image description here

enter image description here

Best Answer

This error typically happens when the call you are making returns an error page that is HTML rather than JSON. System.debug the string before trying to deserialize to see what is going on.

Related Topic