c# - 将 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,是否有一种简单的方法?
解决方案
我认为你应该创建类来定义你想要的 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。
推荐阅读
- c# - 将 ASP.NET Core 托管的 Blazor WASM 5.0.9 部署到 IIS 10
- angular - 一段时间不活动后,为什么会出现 401 错误?
- excel - 给定任意网络链接列表,如何计算背板吞吐量?
- javascript - 将道具传递给孩子反应时出现未定义的错误
- android - 片段中的 registerForActivityResult
- android-studio - Mac Mini M1 找不到合适的图像。确实找到了:... mach-o,但架构错误
- firebase - react-redux-firebase 和 redux-firestore 集成
- date - 如何格式化 InfluxQL Rest API 调用返回的时间
- python - 如何阅读 HTML 电子邮件 - Python
- excel - 目标寻求宏观给出荒谬的答案