Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 14 down vote accepted

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

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


$ curl
{ "s" : "Hello", "i" : 1234 }

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

global class MyService {
    global class MyClass {
        public String s;
        public Integer i;

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

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

        return obj;


$ curl -H "X-PrettyPrint: 1"
  "s" : "Hello",
  "i" : 1234
share|improve this answer
it worked so nice. thanks for huge help – Jie Feb 21 '13 at 0:44

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.