[SalesForce] Extra Backslash in Json String when exposing webservice

I am creating a middle ware in Salesforce. The external System1 calls my SFDC org and I call external system2 from SFDC in turn. The external system2 gives me Json string like {"Car":"Fiat","Model":"2009"}.
I use the following code to return back the json to the calling external system1

//Call external system2 and get response. No DML in between Only Callouts
RestContext.response.addHeader('Content-Type', 'application/json');
return '{"Car":"Fiat","Model":"2009"}';

But i get extra backslash like this in response from SFDC org

"{\"Car\":\"Fiat\",\"Model\":\"2009\"}"

Any solution for this ?

Best Answer

It looks like you are returning a String from your REST endpoint which is then being sanitised by Salesforce JSON serializer.

Any object returned from a method in an @RestResource annotated class is automatically serialized into JSON/XML for you, you don't need to do it yourself.

If you want to return a JSON object from an @RestResource class you have two choices.

Create the object as a class and return an instance of it

global class MyRestObject {
    global String Car;
    global String Model;
}

// Then in your RestResource method
RestContext.response.addHeader('Content-Type', 'application/json');
MyRestObject obj = new MyRestObject();
obj.Car = 'Fiat';
obj.Model = '2009';
return obj;

You will also have the change the return type of you method from String to MyRestObject for this to work. The Salesforce JSON serializer will turn it into JSON for you before it returns it to callers of your REST endpoint.

Set the body directly

RestContext.response.addHeader('Content-Type', 'application/json');
RestContext.response.responseBody = Blob.valueOf('{"Car":"Fiat","Model":"2009"}');

In this case you do have to do the conversion to JSON yourself (or you could use the object from the first example above with JSON.serialize()).

You will also have the change the return type of your method from String to void for this to work. Only return values are run through the Salesforce serializer, so by returning nothing you are telling Salesforce to leave the body of your response alone.

Related Topic