| | | 1 | | using System.Text.Json; |
| | | 2 | | using Microsoft.Extensions.Configuration; |
| | | 3 | | |
| | | 4 | | // ReSharper disable once CheckNamespace |
| | | 5 | | namespace Elsa.Extensions; |
| | | 6 | | |
| | | 7 | | public static class ConfigurationExtensions |
| | | 8 | | { |
| | | 9 | | public static string GetSectionAsJson(this IConfiguration configuration, string sectionKey, JsonSerializerOptions? o |
| | | 10 | | { |
| | 0 | 11 | | var section = configuration.GetSection(sectionKey); |
| | 0 | 12 | | var element = ConvertToJsonElement(section); |
| | 0 | 13 | | return JsonSerializer.Serialize(element, options); |
| | | 14 | | } |
| | | 15 | | |
| | | 16 | | private static JsonElement ConvertToJsonElement(IConfigurationSection section) |
| | | 17 | | { |
| | 0 | 18 | | using var doc = JsonDocument.Parse(JsonSerializer.Serialize(ToObject(section))); |
| | 0 | 19 | | return doc.RootElement.Clone(); |
| | 0 | 20 | | } |
| | | 21 | | |
| | | 22 | | private static object? ToObject(IConfigurationSection section) |
| | | 23 | | { |
| | 0 | 24 | | var children = section.GetChildren().ToList(); |
| | 0 | 25 | | if (!children.Any()) |
| | 0 | 26 | | return section.Value; |
| | | 27 | | |
| | 0 | 28 | | if (children.All(c => int.TryParse(c.Key, out _))) |
| | | 29 | | { |
| | | 30 | | // Treat as array |
| | 0 | 31 | | return children |
| | 0 | 32 | | .OrderBy(c => int.Parse(c.Key)) |
| | 0 | 33 | | .Select(ToObject) |
| | 0 | 34 | | .ToList(); |
| | | 35 | | } |
| | | 36 | | |
| | 0 | 37 | | var dict = new Dictionary<string, object?>(); |
| | 0 | 38 | | foreach (var child in children) |
| | | 39 | | { |
| | 0 | 40 | | dict[child.Key] = ToObject(child); |
| | | 41 | | } |
| | | 42 | | |
| | 0 | 43 | | return dict; |
| | | 44 | | } |
| | | 45 | | } |