【发布时间】:2020-10-24 01:36:15
【问题描述】:
我将一些 IConfiguration 作为 json 存储在我的 sqlserver 数据库中,这样我就可以将它们绑定到一些已经构建的类以提供动态设置。
在某些时候,我可能会在运行时更改新的绑定属性,然后更新数据库。问题是,当我需要时,该类可能具有更多不应绑定且不应序列化的属性。因此,我将 IConfiguration 作为我班级的一个属性。我使用这种方法的另一个原因是我需要从已加载配置的类中提取其他子类,并在我这样做时将它们保存到 db。
问题是,当我序列化 IConfiguration 时,我只会得到一个空的 json 字符串,例如“{}”。 我想我可以利用 .AsEnumerable() 做一些恶作剧,但没有更好的方法吗?
我的示例代码看起来有点像这样
public class ConfigurableClass
{
public int ChildrenCount { get; set; } = 1069;
public bool IsFast { get; set; } = false;
public bool HasChildren { get; set; } = false;
public int Id { get; }
public ConfigurableClass(int id) { Id = id; }
}
static void Main(string[] args)
{
IEnumerable<string> configs = SqlConfigLoader.LoadConfig();
foreach (var str in configs)
{
Console.WriteLine("Parsing new Config:");
var builder = new ConfigurationBuilder();
IConfiguration cfg = builder.AddJsonStream(new MemoryStream(Encoding.Default.GetBytes(str)))
.Build();
var stepExample = new ConfigurableClass(9);
cfg.Bind(stepExample);
//do work with the class that might change the value of binded properties
var updatedCfg = cfg;
Console.WriteLine(JsonSerializer.Serialize(updatedCfg));
Console.WriteLine();
}
Console.ReadLine();
}
编辑
我还尝试了一种不同的方法,将 IConfiguration 转换为这样的嵌套字典
ublic static class IConfigurationExtensions
{
public static Dictionary<string,object> ToNestedDicionary(this IConfiguration configuration)
{
var result = new Dictionary<string, object>();
var children = configuration.GetChildren();
if (children.Any())
foreach (var child in children)
result.Add(child.Key, child.ToNestedDicionary());
else
if(configuration is IConfigurationSection section)
result.Add(section.Key, section.Get(typeof(object)));
return result;
}
}
但我失去了给定 JsonElement 背后的隐式类型:
如果我对结果字典进行序列化,我会得到类似 "Property": "True" 而不是 "Property": true
【问题讨论】:
标签: c# .net .net-core configuration system.text.json