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

    Have you tried setting the correct JSON headers? RestResponse.addHeader('Content-Type', 'application/json');

    Adding Content-Type helped but I thought by default all calls returned JSON but that doesn't seem to be true if I return String. Using Pat's Blob.valueoF with RestResponse.addHeader('Content-Type', 'application/json'); worked.

    great to hear, perhaps best to mark metadaddy his anwser as correct and add the headers to it

    @PJC I think what Vijay is actually trying to do is return an SObject or Apex Class object. I've updated my answer to give the correct method for doing both.

  • 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.

    .Awesome.Nice to learn this .

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM