As with many tools and approaches to solving technical issues, you can often find many ways to achieve the same output. The challenge I was up against was how to serve personalized content as JSON when being served from Sitecore.
The solution below is one way you can achieve this, undoubtedly there are many more!
The over-arching setup
Think of your JSON feed like a Sitecore page. You will need to break a rule of REST as Sitecore personalization requires session, and therefore isn’t stateless. This will need to be reflected in your consuming app, if you don’t provide an identifier every request it will need to understand and persist cookies between requests.
First up you need to select a device, a layout and some renderings. None of this differs to normal Sitecore development. I’ve found for debugging purposes using a new device works better as you can view the content as a web page as well as JSON.
Assuming you’ve decided on a device, you will need to setup a layout:
//note you could easily get the userId from other means e.g. headers / cookies. In fact Querystring isn't great as it shows in path analyzer as different urls.
var userId = Request.QueryString["userId"];
if (Tracker.Current != null && Tracker.Current.Session != null)
Again, much like you would for a page, you can create e.g. Controller Renderings which output the content as you need. One thing to note, these will want to render as JSON e.g.:
|<div class="crayon-line" id="crayon-5c6f022e854cd899951794-1"><span class="crayon-sy">@</span><span class="crayon-e">model <span class="crayon-sy">.</span>
These components can have datasources setup as normal, and hence personalization is available into your JSON feed.
Via a browser you would then load the url as normal, remembering to specify the device you’ve selected and you should see content based off rules, user information and behaviours and more.
Taking it to the next level
The simpler approach assumes you have one component per page. Complexity comes in when you need to generate valid JSON based off multiple controls – this can be achieved but requires you to either configure things via rendering parameters or at the point the page is rendered, interrogate the counterpart presentation components and work out whether you have sibling controls.
If you find you have sibling components to render you’d need to add commas after your controls to ensure valid JSON.