【问题标题】:Exporting/Serializing configurable Fields导出/序列化可配置字段
【发布时间】:2020-12-02 12:36:48
【问题描述】:

我需要根据用户在 app.config 中设置的配置序列化属性(HTTP POST 到另一个服务)。 在 C# 中实现这一目标的最佳方法是什么。

例子

public Class Student { 

public string Name {get; set;}
public string Grade { get, set}
public string Address {get; set}

}

用户可以配置设置文件。例如:

<appSettings>
 <add key="ExportName" value="true"/>
 <add key="ExportGrade" value="true"/>
 <add key="ExportAddress" value="false"/>
</appSettings>

在这种情况下,我不想序列化/导出地址。有没有办法我可以使用 JsonIgnore 或类似的东西?

【问题讨论】:

  • 一种方法是编写自定义转换器。在自定义转换器中,获取您的配置数据并在运行时执行所需的序列化。
  • 如果您可以发布示例代码或指向某些链接会很好

标签: c# .net json asp.net-web-api serialization


【解决方案1】:

如下重写你的导出配置:

 <appSettings>
     <add key="Student.Name.Export" value="true"/>
     <add key="Student.Grade.Export" value="true"/>
     <add key="Student.Address.Export" value="false"/>
 </appSettings>

然后将配置加载为Dictionary&lt;String, Boolean&gt;(请记住,在这里使用字典只会使用它的数据结构,并且绝不会从它的查找表性能中受益)。

此时,您可以自动化您的序列化过程:

public static String SerializeObject<T>(T obj, Dictionary<String, Boolean> conf)
{
    Type typeofT = typeof(T);
    Regex exp = new Regex($"{typeofT}.*.Export");
    IEnumerable<(String Key, Boolean Value)> peropertyConfigurations =
        from pair in conf
        where exp.IsMatch(pair.Key) && pair.Value == true
        select (pair.Key, pair.Value);

    // CAUTION: This does not work if your property is a reference to another Model/Type
    // In that case you have to loop through the nested type as well.
    IEnumerable<PropertyInfo> queryProperties = 
        from property in typeofT.GetProperties()
        join propertyConfiguration in peropertyConfigurations
        on property.Name equals propertyConfiguration.Key
        select property;
    T filteredObject = Activator.CreateInstance<T>();
    foreach(var property in queryProperties){
        property.SetValue(filteredObject, property.GetValue(obj));
    }
    return System.Text.Json.JsonSerializer.Serialize(filteredObject);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 2023-01-15
    • 2012-07-05
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多