How can I return JSON object from REST service?

I used JSONGenerator to generate a customized JSON String. I know I can return sObject or String using Salesforce REST. But now I am sure I do not want to return sObject because I want the customized format. But I also do not want to return a String because client app is expecting a strict JSON object. How can I solve this?

Answer

If you have a JSON object as a String, you can return it by assigning it to the responseBody, like this:

@RestResource(urlMapping='/MyService/*')
global class MyService {
    @HttpGet
    global static void sayHello() {
        RestContext.response.addHeader('Content-Type', 'application/json');
        RestContext.response.responseBody = Blob.valueOf('{ "s" : "Hello", "i" : 1234 }');
    }
}

Result:

$ curl https://superpat-developer-edition.na3.force.com/services/apexrest/superpat/HelloService
{ "s" : "Hello", "i" : 1234 }

Alterntively, you can define an inline Apex class with the format you require. For example:

@RestResource(urlMapping='/MyService/*')
global class MyService {
    global class MyClass {
        public String s;
        public Integer i;

        public MyClass(String s, Integer i) {
            this.s = s;
            this.i = i;
        }
    }

    @HttpGet
    global static MyClass sayHello() { 
        MyClass obj = new MyClass('Hello', 1234);

        return obj;
    }
}

yields

$ curl -H "X-PrettyPrint: 1" https://superpat-developer-edition.na3.force.com/services/apexrest/superpat/MyService
{
  "s" : "Hello",
  "i" : 1234
}

Attribution
Source : Link , Question Author : Jie , Answer Author : metadaddy

Leave a Comment