【发布时间】:2019-04-28 04:52:27
【问题描述】:
动态创建类属性的最佳方法是什么?
我必须创建基于 JSON 数据的 webhook 推送消息。 我创建了 2 个类,每个类都有多个属性,问题是即使没有填充属性(默认为 NULL),webhook push 格式错误。为避免这种情况,我必须根据需要创建属性。
有没有什么方法可以做到这一点? 描绘我需要的东西:
public class ChannelSettings
{
public string channel { get; set; }
public string username { get; set; }
public string text { get; set; }
public AttachSettings attachments { get; set; } //Here I would like to this property to be dynamic
}
public class AttachSettings
{
public string fallback { get; set; }
public string pretext { get; set; }
public string text { get; set; }
public string title { get; set; }
public string author_name { get; set; }
public string image_url { get; set; }
public string author_icon { get; set; }
}
public string GenJSON(ChannelSettings channelSet)
{
string output = JsonConvert.SerializeObject(channelSet);
return output;
}
【问题讨论】:
-
如果您添加一些示例数据以及您期望 JSON 的样子,这将更容易可视化...
-
"webhook push has wrong format" 我不明白这是什么意思。能否提供一些示例数据?
-
even if property is not filled (NULL by default)。你确定吗?似乎该属性存在于json中。否则不会有问题。 IMO 问题不应该是how to add a property to a class,而是how to define the properties that need to be serialized。 -
好的,所以基本上如果没有添加附加数据,那么我就有了那种 JSON:"{\"channel\":null,\"username\":\"user\" ,\"text\":\"test text\",\"attachments\":[{\"fallback\":null,\"pretext\":null,\"text\":null,\"title\ ":null,\"author_name\":null,\"image_url\":null,\"author_icon\":null,\"fields\":[]}]}",我想要的是:" {\"channel\":null,\"username\":\"user\",\"text\":\"test text\"}" 所以在没有数据的情况下不需要attachment section
标签: c# dynamic properties