I want to return a JSON from my Apex Rest web service. There is a list of objects I must return. If I just make the return type of the method as

return myCustObjList

Edit here goes the datatype:

List<BusinessPartnerUpdateResult> myCustObjList = new 

global class BusinessPartnerUpdateResult {
    global String SalesforceID {get; set;}
    global String success {get; set;}
    global List<ErrorDetails> errors {get; set;}
global class ErrorDetails {
    global String errorCode {get; set;}
    global String errorMessage {get; set;}

Here is how it gets populated... inside a loop of Database.SaveResult:

eachBusinessPartnerUpdateResult.SalesforceID = saveResult.getId();
if (saveResult.isSuccess()) {
    businessPartnerUpdateResult.success = 'true';


It works fine and in the Java caller I am getting back a nice JSON like this:

        "success": "true",
        "SalesforceID": "0011r00001mIDEPAA4",
        "errors": null
    }, {
        "success": "true",
        "SalesforceID": "0011r00001mIDEFAA4",
        "errors": null
    }, {
        "success": "true",
        "SalesforceID": "0011r00001mIDEAAA4",
        "errors": null

However, I wish to wrap the whole list in a JSON object and return that object instead.

So instead of return myCustObjList I have written this in my WS:

JSONGenerator gen = JSON.createGenerator(false);
gen.writeObjectField('syncResults', myCustObjList);
return gen.getAsString();

and changed the webservice method return type to String.

Now what Java gets back is this:


Why are there so many backslash escape characters? Can I not get just the simple JSON as String minus the backslashes? I have tried JSONGenerator "pretty" version, then I get back lots of \n, I do not want that either.

Can anyone help please?

  • Just added definition.. Commented Apr 6, 2018 at 7:11
  • Added code as to how it gets populated too .. Commented Apr 6, 2018 at 7:14

1 Answer 1


To remove the backslash you have to write the blob value of the JSON String into the body directly in the RestContext. You will have to change the return type of your method from String to void.

global with sharing class MyRestResource {
    global static void doGet() {
        List<Account> accList = [SELECT Id, Name, Phone, Website FROM Account];
        JSONGenerator gen = JSON.createGenerator(false);
        gen.writeObjectField('syncResults', accList);
        String jsonStr = gen.getAsString();
        RestContext.response.addHeader('Content-Type', 'application/json');
        RestContext.response.responseBody = Blob.valueOf(jsonStr);        
  • This is exactly what I was looking for. Thanks so much. Commented Apr 6, 2018 at 10:17
  • Thats a fantastic suggestion..Thanks Saroj
    – Varun
    Commented Nov 18, 2022 at 23:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .