[SalesForce] JSON String in response shows up with quotes

I use a REST Apex service and return String from the method. The client call to the REST API returns with qoutes around the reqult like this example: "…result.." and also with \" inside the result.How do I get rid of the quotes ? I saw Pat's blog about using Blob.valueOf(..) but I want to return a JSONObject like a String as you would do in Jersey.

@HttpGet
global static String getAllEmployeeDataForContact() { 
       return JSON.serialize(.....)

TIA

Best Answer

Quotes will come anyway, you don't need to use JSON.serialise with Apex web REST services, they take care of format XML/JSON automatically, so returning the type directly would work. Here is the sample, that I tried and is working fine.

@RestResource(urlMapping='/stacke/*')
global class SampleWebService {

    @httpget
    global static String getAllEmployeeDataForContact() { 
           return 'hello world';
    }

}

Result is coming with double quotes as you said and its correct as well

"hello world"

But this is not a JSON string actually try converting it to some wrapped type for easy consumption by clients like

@RestResource(urlMapping='/stacke/*')
global class SampleWebService {

    global class Result {
        global String response{get;set;}
    }
    @httpget
    global static Result getAllEmployeeDataForContact() { 
            Result r = new Result();
            r.response = 'hello world';
           return r;
    }

}

This returns a JSON string like this

{
    "response": "hello world"
}

Hope this helps.

Related Topic