[SalesForce] JSONGenerator issue

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 
List<BusinessPartnerUpdateResult>();

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.writeStartObject();
gen.writeObjectField('syncResults', myCustObjList);
gen.writeEndObject();
return gen.getAsString();

and changed the webservice method return type to String.

Now what Java gets back is this:

"{\"syncResults\":[{\"success\":\"true\",\"SalesforceID\":\"0011r00001mIDEPAA4\",\"errors\":null},{\"success\":\"true\",\"SalesforceID\":\"0011r00001mIDEFAA4\",\"errors\":null},{\"success\":\"true\",\"SalesforceID\":\"0011r00001mIDEAAA4\",\"errors\":null}]}"

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?

Best Answer

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.

@RestResource(urlMapping='/myrestservice/*')
global with sharing class MyRestResource {
    @HttpGet
    global static void doGet() {
        List<Account> accList = [SELECT Id, Name, Phone, Website FROM Account];
        JSONGenerator gen = JSON.createGenerator(false);
        gen.writeStartObject();
        gen.writeObjectField('syncResults', accList);
        gen.writeEndObject();
        String jsonStr = gen.getAsString();
        RestContext.response.addHeader('Content-Type', 'application/json');
        RestContext.response.responseBody = Blob.valueOf(jsonStr);        
    }
}