Last active
November 8, 2021 17:37
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@*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)) |
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;
}
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
Hi, is it possible to turn JSON found in the PreviewXML table into HTML?