使用Razor使用Umbraco模板输出JSON

时间:2012-10-10 10:31:58

标签: json razor umbraco

我遇到过需要复制某些JSON的情况,以便网站的某个区域可以进行内容管理。我有一个需要复制的 json 文件。该网站的分类是复杂的,不幸的是我无法改变这一点。

我在Umbraco中设置了模板,我想要的数据显示在页面上,但我不知道如何将其转换为输出为JSON。

Razor看起来像这样:

    @{
    dynamic memberships = Library.NodeById(1081);
    var packageGroups =  memberships.Descendants("Price");
    foreach(var package in packageGroups) {
        var top = package.AncestorOrSelf("Type");
        var Description = (@top.HasValue("Blurb")) ? @top.Blurb : @top.Description;
        var Locations = "";

        foreach(var item in package.UserLocation.ToString().Split(',')) {
            Locations += @Model.NodeById((@item)).Name;
            Locations += ",";
        }

        <ul>
            <li>Maintitle: @top.Parent().Title</li>
            <li>Title: @top.Title</li>
            <li>SubTitle: @SubTitle</li>
            <li>Description: @Description</li>
            <li>Link: @top.Url</li>
            <li>Location: @Locations</li>
            <li>Render: true</li>
        </ul>
    }
}

我需要输出它来复制JSON文件,如下所示:

   {
       "items":[
          {
             "MainTitle":"Package Top Level Title",
             "Title":"Package Title",
             "SubTitle":"Additional Details",
             "Description":"We wil provide you with some great products and services.",
             "Link":"/path/to/package/",
             "Location":[
                "Saturn"
             ],
             "Render":true
          },
       ]
}
指针赞赏。

1 个答案:

答案 0 :(得分:9)

您可以将属性加载到匿名对象中,然后对其进行序列化。这样的事情应该有效(未经测试):

@{
    var items = new List<dynamic>();
    dynamic memberships = Library.NodeById(1081);
    var packageGroups =  memberships.Descendants("Price");
    foreach(var package in packageGroups)
    {
        var top = package.AncestorOrSelf("Type");
        var Description = (top.HasValue("Blurb")) ? top.Blurb : top.Description;
        var Locations = new List<string>();

        foreach(var item in package.UserLocation.ToString().Split(','))
        {
            Locations.Add(Model.NodeById(item).Name);
        }

        items.Add(new
        {
            Maintitle = top.Parent().Title,
            Title = top.Title,
            SubTitle = SubTitle,
            Description = Description,
            Link = top.Url,
            Location = Locations,
            Render = true
        });
    }

    var o = new {
        items = items
    };

    string json = Json.Encode(o);
    Response.ContentType = "application/json";
}
@Html.Raw(json)

匿名对象的替代方法是使用Dictionary。但我认为匿名对象在这种情况下会很好用。