Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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

1 Answer 1

up vote 6 down vote accepted

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
}
share|improve this answer
    
it worked so nice. thanks for huge help –  Jie Feb 21 '13 at 0:44

Your Answer

 
discard

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.