如何将 IConfigurationRoot 或 IConfigurationSection 转换为 JObject/JSON

2023-11-22

我的代码中有以下代码Program.cs:

var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("clientsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"clientsettings.{host.GetSetting("environment")}.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables()
                .Build();

我想将构建配置的结果转换为 JObject\Json 以发送到客户端。我该怎么做? 我不想为我的设置创建自定义类。

我的答案: merge

public static JObject GetSettingsObject(string environmentName)
    {
        object[] fileNames = { "settings.json", $"settings.{environmentName}.json" };


        var jObjects = new List<object>();

        foreach (var fileName in fileNames)
        {
            var fPath = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + fileName;
            if (!File.Exists(fPath))
                continue;

            using (var file = new StreamReader(fPath, Encoding.UTF8))
                jObjects.Add(JsonConvert.DeserializeObject(file.ReadToEnd()));
        }


        if (jObjects.Count == 0)
            throw new InvalidOperationException();


        var result = (JObject)jObjects[0];
        for (var i = 1; i < jObjects.Count; i++)
            result.Merge(jObjects[i], new JsonMergeSettings
            {
                MergeArrayHandling = MergeArrayHandling.Merge
            });

        return result;
    }

由于配置实际上只是一个键值存储,其中键具有某种格式来表示路径,因此将其序列化回 JSON 并不那么简单。

您可以做的是递归遍历配置子项并将其值写入JObject。这看起来像这样:

public JToken Serialize(IConfiguration config)
{
    JObject obj = new JObject();
    foreach (var child in config.GetChildren())
    {
        obj.Add(child.Key, Serialize(child));
    }

    if (!obj.HasValues && config is IConfigurationSection section)
        return new JValue(section.Value);

    return obj;
}

请注意,这对输出的外观极为有限。例如,数字或布尔值(JSON 中的有效类型)将表示为字符串。由于数组是通过数字键路径表示的(例如key:0 and key:1),您将获得作为索引字符串的属性名称。

我们以下面的 JSON 为例:

{
  "foo": "bar",
  "bar": {
    "a": "string",
    "b": 123,
    "c": true
  },
  "baz": [
    { "x": 1, "y": 2 },
    { "x": 3, "y": 4 }
  ]
}

这将通过以下关键路径在配置中表示:

"foo"      -> "bar"
"bar:a"    -> "string"
"bar:b"    -> "123"
"bar:c"    -> "true"
"baz:0:x"  -> "1"
"baz:0:y"  -> "2"
"baz:1:x"  -> "3"
"baz:1:y"  -> "4"

因此,上述结果的 JSONSerialize方法如下所示:

{
  "foo": "bar",
  "bar": {
    "a": "string",
    "b": "123",
    "c": "true"
  },
  "baz": {
    "0": { "x": "1", "y": "2" },
    "1": { "x": "3", "y": "4" }
  }
}

因此,这将不允许您取回原始表示形式。话虽这么说,当再次读取生成的 JSON 时Microsoft.Extensions.Configuration.Json,那么它will结果相同的配置对象。那么你can使用它将配置存储为 JSON。

如果您想要比这更漂亮的东西,则必须添加逻辑来检测数组和非字符串类型,因为这两者都不是配置框架的概念。


我想合并appsettings.json and appsettings.{host.GetSetting("environment")}.json到一个对象[并将其发送给客户端]

请记住,特定于环境的配置文件通常包含不应离开计算机的秘密。对于环境变量来说尤其如此。如果要传输配置值,请确保在构建配置时不包含环境变量。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 IConfigurationRoot 或 IConfigurationSection 转换为 JObject/JSON 的相关文章

随机推荐