Can I build some XML or JSON in Apex and then redirect to it from a method that returns a PageReference object?

public PageReference saveText() {
    PageReference p = new PageReference(someJSONObject);
    return p;

Is anything like this possible?

  • you can try using metadata api to create/save a page from the json and then redirect to the page you just saved. – Vamsi Krishna Gosu Jan 27 '16 at 2:56
  • Got any documentation on it handy? – okay56k Jan 27 '16 at 3:06

No, a PageReference isn't content, it's just a reference to some content, which Visualforce then redirects the user to. You could render your json in a Visualforce page and specify the mime type, for example:

<apex:page applyHtmlTag="false" showHeader="false" contentType="application/json" 

However, if you need to return JSON or XML in this manner, you would probably be better off using Apex REST to write a class that handles HTTP requests & responses directly, without invoking Visualforce. And since Apex REST exposes your class at a public URL, you can always return a PageReference to the URL from your controller if you have a use case that does require redirecting from a VF page to an API end point.

  • Yeah, I explored that, but the lack of auth. options with my other app limit my options severely. – okay56k Jan 27 '16 at 3:15
  • Hold up, what about this? it.toolbox.com/blogs/anything-worth-doing/… – okay56k Jan 27 '16 at 3:35
  • Looks like they are doing what I showed in my example- generating the actual output via Visualforce. The page reference they return (PageReference aPage = Page.AccountContactsXML;) is a reference to the Visualforce page named "AccountContactsXML", which iterates through the controller data to output xml. Note the use of contentType in the vf page tag to specify mime type. – Jason Clark Jan 27 '16 at 3:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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