18

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?

1 Answer 1

32

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
}
1
  • 1
    Important note for the second example. You have you add .json to the end to get it to return JSON in a browser. Crome does not send accept header of json and apparently salesforce is super strict and will still return XML even if you set the response content type to application/json
    – TehNrd
    Apr 15, 2023 at 16:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .