首页 > 解决方案 > 将 Umbraco IContent 转换为 JSON

问题描述

即使在发布时,我也可以IContent通过侦听器处理来自 Umbraco 的对象

public static IContent[] FaqEntities(this PublishEventArgs<IContent> publishEventArgs)
        {
            return publishEventArgs.PublishedEntities.Where(x => x.ContentType.Name == "FAQ").ToArray();
        }

在 C# 中,我想JSON从返回的数组中的已发布文档中创建一个包含选定属性(别名和值)的文件 - 是否有一种简单的方法可以序列化 UmbracoIContent对象以获得我需要的 JSON 输出?

var json = JsonConvert.SerializeObject(faqEntities)并且 var json = Json.Encode(faqEntities)只给了我整个对象,但我希望创建一个类似于

{
    "faqs": [{
            "nodeId": 1,
            "question": "My Password is incorrect?",
            "answer": "If you have forgotten or lost your password, please click on the Forgotten Password link on the Login page and follow the instructions shown."
        },
        {
            "nodeId": 2,
            "question": "How can I edit my personal details?",
            "answer": "You can blah blah blah....."
        },
        {
            "nodeId": 3,
            "question": "What is an ABC?",
            "answer": "An ABC is where you can....."
        }
    ]
}

一旦检索到 IContent 以转换为 JSON,是否有一种简单的方法?

标签: c#jsonumbracoumbraco7

解决方案


我认为你应该创建类来定义你想要的 json,然后你可以选择新的格式。就像是:

public class Faq
{
     public int nodeId { get; set; }
     public string question { get; set; }
     public string answer { get; set; }
}

public class FaqCollection
{
     public IList<Faq> faqs { get; set; }
}

然后填充对象:

var faqsCollection = new FaqCollection();
faqsCollection.faqs = faqEntities.Select(y => new Faq { nodeId = y.nodeId, question = y.question, answer = y.answer }).ToList();

根据您的需要,您甚至可能不必在执行此操作之前转换为 json。


推荐阅读