1

I have a simple rest resource that takes in a list of Contract objects and just prints out some information about them.

@RestResource(urlMapping='/contracttest/*')
global with sharing class ContractTest {

    @HttpPut
    global static void contractPrint(List<Contract> contracts)
    {
        System.debug('service Contracts - ' + contracts);

        for(Contract con : contracts)
        {
            System.Debug('Id - ' + con.Id);
        }       
    }
}

Where I am struggling with the documentation is how do you call this service with a list of Contracts that you use serialize yourself and get the automatic deserialization to work. I am just calling this from an anonymous window with a simple list of contracts I have selected from the database.

The problem I run into is if I take a list of contracts created like so:

List<contract> contracts = [SELECT id FROM Contract LIMIT 5];
JSON.Serialize(contracts);

I get a json string that does not serialize properly with the rest resource I have created. Is there a way to the JSON.Serialize() method with a RestResource that takes a list of SObjects?

Calling with the following anonymous code gives me an HTTP 400.

    HttpRequest req = new HttpRequest();
    HttpResponse res = new HttpResponse();
    Http http = new Http();

    req.setEndpoint(Url.getSalesforceBaseUrl().ToExternalForm() + '/services/apexrest/contracttest');
    List<contract> contracts = [SELECT id FROM Contract LIMIT 5];
    req.setHeader('Authorization', 'OAuth '+UserInfo.getSessionId());
    req.setHeader('content-type', 'application/json');
    req.setMethod('PUT');
    req.setBody(JSON.Serialize(contracts));
    System.Debug(req.getBody());
    res = http.send(req);
    System.Debug('Response body - ' + res.getBody());

The error

DEBUG|Response body - [{"message":"JSON request body must be an object at [line:1, column:2]","errorCode":"JSON_PARSER_ERROR"}]

Thanks

  • 1
    Can you try adding <code>req.setBody('{"contracts":'+JSON.serialize(contracts)+'}');</code>. I guess the JSON format is expecting the same varriable name as the first field in the request JSON. – Saumya Ranjan Satapathy Mar 29 '17 at 13:26
  • 1
    Saumya, That works. I had tried that previously but had double quotes around the serialized string, so that was breaking it. Thanks, you should create an answer for that. – grantk Mar 29 '17 at 13:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.