Sign up ×
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 11 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.