| | | 1 | | using System.Text.Json; |
| | | 2 | | using System.Text.Json.Serialization; |
| | | 3 | | using Microsoft.Extensions.Configuration; |
| | | 4 | | |
| | | 5 | | namespace Elsa.Common.Serialization; |
| | | 6 | | |
| | | 7 | | public class ConfigurationJsonConverter : JsonConverter<IConfiguration> |
| | | 8 | | { |
| | | 9 | | public override IConfiguration? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| | | 10 | | { |
| | 0 | 11 | | var jsonElement = JsonElement.ParseValue(ref reader); |
| | 0 | 12 | | using var memoryStream = new MemoryStream(); |
| | 0 | 13 | | using var writer = new Utf8JsonWriter(memoryStream); |
| | 0 | 14 | | jsonElement.WriteTo(writer); |
| | 0 | 15 | | writer.Flush(); |
| | 0 | 16 | | memoryStream.Position = 0; |
| | | 17 | | |
| | 0 | 18 | | var configurationBuilder = new ConfigurationBuilder(); |
| | 0 | 19 | | configurationBuilder.AddJsonStream(memoryStream); |
| | 0 | 20 | | return configurationBuilder.Build(); |
| | 0 | 21 | | } |
| | | 22 | | |
| | | 23 | | public override void Write(Utf8JsonWriter writer, IConfiguration value, JsonSerializerOptions options) |
| | | 24 | | { |
| | 0 | 25 | | var dictionary = new Dictionary<string, object?>(); |
| | 0 | 26 | | foreach (var child in value.GetChildren()) |
| | 0 | 27 | | dictionary[child.Key] = GetValue(child); |
| | | 28 | | |
| | 0 | 29 | | JsonSerializer.Serialize(writer, dictionary, options); |
| | 0 | 30 | | } |
| | | 31 | | |
| | | 32 | | private static object? GetValue(IConfigurationSection section) |
| | | 33 | | { |
| | 0 | 34 | | var children = section.GetChildren().ToList(); |
| | | 35 | | |
| | 0 | 36 | | if (!children.Any()) |
| | 0 | 37 | | return section.Value; |
| | | 38 | | |
| | 0 | 39 | | var dict = new Dictionary<string, object?>(); |
| | 0 | 40 | | foreach (var child in children) |
| | 0 | 41 | | dict[child.Key] = GetValue(child); |
| | | 42 | | |
| | 0 | 43 | | return dict; |
| | | 44 | | } |
| | | 45 | | } |