0

I need to sync some account records between two environments of the salesforce. I'm able to make a callout but while passing data getting a JSON error. I'm basically serializing a list of accounts in the source, which I intend to deserialize in the destination.

Source Method:

List<Account> accountList = new List<Account>();
    string jsonstr = JSON.serialize(accountList);
            Http h1 = new Http();
            HttpRequest req1 = new HttpRequest();
            req1.setHeader('Authorization','Bearer '+'!sessionId');
            req1.setHeader('Content-Type','application/json');
            req1.setHeader('accept','application/json');
            
            req1.setBody(jsonstr);//Send JSON body
            req1.setMethod('POST');
            req1.setEndpoint('https://test.salesforce.com/services/apexrest/accountSync');
            HttpResponse res1 = h1.send(req1);

Destination:

@HttpPost
    global static string sampleRequestMethod(string accList) {
        system.debug('>>> accList... '+accList);
        
        return 'Success';
    }
1
  • 4
    Do you get an error message? Please be as detailed as possible about the error you receive. – Adrian Larson Mar 1 at 0:52
2

Your problem is that the far end is using a string parameter. This means that the JSON is expected to have a top-level property that corresponds to the parameter, as in:

{ "accList": [ { ... }, { ... } ] }

You can read more about it in the Apex REST Methods documentation.

To make the JSON match what's expected, do this:

string jsonstr = JSON.serialize(new Map<String, Object> { 'accList' => accountList });

If you want to send your JSON as is, make sure you use RestContext.request.requestBody.toString() instead of using the parameterized deserialization method.

@HttpPost
global static string sampleRequestMethod() {
  String jsonBody = RestContext.request.requestBody.toString();
  // etc //
}

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.