导出/序列化可配置字段

问题描述

我需要基于用户在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或类似的东西吗?

解决方法

按如下所示重写导出配置:

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

然后将配置作为Dictionary<String,Boolean>加载(请记住,在这里使用字典只能使用其数据结构,而绝不能从其查询表性能中受益)。

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

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);
}