【发布时间】:2016-07-14 14:25:19
【问题描述】:
我对 EpiServer 完全陌生,这已经让我死了好几天:(
我正在寻找一种将页面及其所有后代转换为 JSON 树的简单方法。
我已经走到这一步了:
public class MyPageController : PageController<MyPage>
{
public string Index(MyPage currentPage)
{
var output = new ExpandoObject();
var outputDict = output as IDictionary<string, object>;
var pageRouteHelper = ServiceLocator.Current.GetInstance<EPiServer.Web.Routing.PageRouteHelper>();
var pageReference = pageRouteHelper.PageLink;
var children = DataFactory.Instance.GetChildren(pageReference);
var toOutput = new { };
foreach (PageData page in children)
{
outputDict[page.PageName] = GetAllContentProperties(page, new Dictionary<string, object>());
}
return outputDict.ToJson();
}
public Dictionary<string, object> GetAllContentProperties(IContentData content, Dictionary<string, object> result)
{
foreach (var prop in content.Property)
{
if (prop.IsMetaData) continue;
if (prop.GetType().IsGenericType &&
prop.GetType().GetGenericTypeDefinition() == typeof(PropertyBlock<>))
{
var newStruct = new Dictionary<string, object>();
result.Add(prop.Name, newStruct);
GetAllContentProperties((IContentData)prop, newStruct);
continue;
}
if (prop.Value != null)
result.Add(prop.Name, prop.Value.ToString());
}
return result;
}
}
问题是,通过将页面结构转换为Dictionaries,我的页面中的JsonProperty PropertyName注解丢失了:
[ContentType(DisplayName = "MySubPage", GroupName = "MNRB", GUID = "dfa8fae6-c35d-4d42-b170-cae3489b9096", Description = "A sub page.")]
public class MySubPage : PageData
{
[Display(Order = 1, Name = "Prop 1")]
[CultureSpecific]
[JsonProperty(PropertyName = "value-1")]
public virtual string Prop1 { get; set; }
[Display(Order = 2, Name = "Prop 2")]
[CultureSpecific]
[JsonProperty(PropertyName = "value-2")]
public virtual string Prop2 { get; set; }
}
这意味着我得到这样的 JSON:
{
"MyPage": {
"MySubPage": {
"prop1": "...",
"prop2": "..."
}
}
}
而不是这个:
{
"MyPage": {
"MySubPage": {
"value-1": "...",
"value-2": "..."
}
}
}
我知道使用自定义 ContractResolvers 进行 JSON 序列化,但这对我没有帮助,因为我需要无法从 C# 属性名称推断的 JSON 属性名称。
我还希望能够为页面本身设置自定义 JSON 属性名称。
我真的希望友好的 EpiServer 大师可以在这里帮助我!
提前致谢:)
【问题讨论】:
-
您能否更新您的问题以包括 ToJson 实现,我提出的一个建议是将
Dictionary<string, object>更改为Dictionary<string, MySubPage> -
我只是在 Index 方法的末尾使用
outputDict.ToJson();。关于您的建议,我想我可以这样做:var newStruct = new Dictionary<string, prop.GetType()>();我不确定这会有所帮助吗? -
更新:我现在正在试用 JOS.Content.Json。希望这会有所帮助。如果是这样,我将发布我的解决方案。 github.com/joseftw/JOS.ContentJson