将Umbraco IContent转换为JSON

时间:2018-04-27 11:57:19

标签: c# json umbraco umbraco7

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

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

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

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

的JSON文件
{
    "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,是否有一种简单的方法?

1 个答案:

答案 0 :(得分:0)

我认为你应该创建类来定义你想要的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。