Skip to content

Instantly share code, notes, and snippets.

@EdCharbeneau
Last active November 8, 2021 17:37
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save EdCharbeneau/702a4c2d702d30f371bd to your computer and use it in GitHub Desktop.
Save EdCharbeneau/702a4c2d702d30f371bd to your computer and use it in GitHub Desktop.
Turn any Umbraco content into a JSON object by using a Razor template
@*Experimental, I'm still fairly new to Umbraco there could be an API avialbe for this already.
This was inspired by http://cultiv.nl/blog/razor-vs-base-to-output-json-in-umbraco/
If there is a better way please let me know via twitter @EdCharbeneau
Add this template to your Umbraco site and any content can be called via Ajax using
/mySite/contentPath/?alttemplate=AsJson
Return value will be { propertyAlias : value }
Ex: { "personAlias" : "John Doe", "id" : 1002 }
*@
@using Newtonsoft.Json;
@using System.Dynamic;
@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
Layout = null;
Response.ContentType = "application/json";
dynamic exObj = new ExpandoObject();
var dictionary = exObj as IDictionary<string, object>;
Model.Content.Properties.ForEach(p => dictionary[p.PropertyTypeAlias] = p.Value);
}
@Html.Raw(JsonConvert.SerializeObject(exObj))
@jonathanS8080
Copy link

Hi, is it possible to turn JSON found in the PreviewXML table into HTML?

@JJCLane
Copy link

JJCLane commented May 10, 2017

Hi, I ran into an issue when trying to use this to serialise an Umbraco model that contains a node reference, as it causes a circular reference issue. I came up with this solution:

dynamic GetProperties(ICollection<IPublishedProperty> props)
    {
        dynamic exObj = new System.Dynamic.ExpandoObject();
        var dictionary = exObj as IDictionary<string, object>;
        foreach (var prop in props)
        {
            var umbracoNodes = prop.Value as List<IPublishedContent>;

            if (umbracoNodes != null)
            {
                var tmpDictionaries = new List<dynamic>();
                foreach(var umbracoNode in umbracoNodes)
                {
                    tmpDictionaries.Add(GetProperties(umbracoNode.Properties));
                }
                dictionary[prop.PropertyTypeAlias] = tmpDictionaries;
                continue;
            }
            dictionary[prop.PropertyTypeAlias] = prop.Value.ToString();
        }
        return dictionary;
    }

@Debet
Copy link

Debet commented Nov 15, 2017

JJCLane can you post the complete solution?
I can't figure out how to apply your solution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment