| | | 1 | | using System.Text.Json; |
| | | 2 | | using System.Text.Json.Serialization; |
| | | 3 | | using Elsa.Expressions.Contracts; |
| | | 4 | | |
| | | 5 | | namespace Elsa.Workflows.Serialization.Converters; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// A converter that can convert a dictionary of string keys and object values while preserving the object type. |
| | | 9 | | /// </summary> |
| | | 10 | | public class PolymorphicDictionaryConverter : JsonConverter<IDictionary<string, object>> |
| | | 11 | | { |
| | | 12 | | private readonly JsonConverter<object> _objectConverter; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | 16054 | 15 | | public PolymorphicDictionaryConverter(JsonSerializerOptions options, IWellKnownTypeRegistry wellKnownTypeRegistry) |
| | | 16 | | { |
| | 145545 | 17 | | var factory = (JsonConverterFactory)(options.Converters.FirstOrDefault(x => x is PolymorphicObjectConverterFacto |
| | 16054 | 18 | | _objectConverter = (JsonConverter<object>)factory.CreateConverter(typeof(object), options)!; |
| | 16054 | 19 | | } |
| | | 20 | | |
| | | 21 | | /// <inheritdoc /> |
| | | 22 | | public override IDictionary<string, object> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOption |
| | | 23 | | { |
| | 9310 | 24 | | if (reader.TokenType != JsonTokenType.StartObject) |
| | 0 | 25 | | throw new JsonException("Expected start of object."); |
| | | 26 | | |
| | 9310 | 27 | | var dictionary = new Dictionary<string, object>(); |
| | | 28 | | |
| | 19375 | 29 | | while (reader.Read()) |
| | | 30 | | { |
| | 19375 | 31 | | if (reader.TokenType == JsonTokenType.EndObject) |
| | 9310 | 32 | | return dictionary; |
| | | 33 | | |
| | 10065 | 34 | | var key = reader.GetString()!; |
| | 10065 | 35 | | reader.Read(); |
| | 10065 | 36 | | var value = _objectConverter.Read(ref reader, typeof(object), options)!; |
| | 10065 | 37 | | dictionary.Add(key, value); |
| | | 38 | | } |
| | | 39 | | |
| | 0 | 40 | | throw new JsonException("Expected end of object."); |
| | | 41 | | } |
| | | 42 | | |
| | | 43 | | /// <inheritdoc /> |
| | | 44 | | public override void Write(Utf8JsonWriter writer, IDictionary<string, object> value, JsonSerializerOptions options) |
| | | 45 | | { |
| | 10448 | 46 | | writer.WriteStartObject(); |
| | | 47 | | |
| | 25000 | 48 | | foreach (var kvp in value) |
| | | 49 | | { |
| | 2052 | 50 | | writer.WritePropertyName(kvp.Key); |
| | 2052 | 51 | | _objectConverter.Write(writer, kvp.Value, options); |
| | | 52 | | } |
| | | 53 | | |
| | 10448 | 54 | | writer.WriteEndObject(); |
| | 10448 | 55 | | } |
| | | 56 | | } |