| | | 1 | | using System.Text.Json; |
| | | 2 | | using System.Text.Json.Serialization; |
| | | 3 | | using Elsa.Expressions.Contracts; |
| | | 4 | | using Elsa.Workflows.Memory; |
| | | 5 | | using Elsa.Workflows.Models; |
| | | 6 | | using Microsoft.Extensions.Logging; |
| | | 7 | | |
| | | 8 | | namespace Elsa.Workflows.Serialization.Converters; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// Serializes <see cref="Type"/> objects to a simple alias representing said type. |
| | | 12 | | /// </summary> |
| | | 13 | | public class VariableConverter : JsonConverter<Variable> |
| | | 14 | | { |
| | | 15 | | private readonly VariableMapper _mapper; |
| | | 16 | | private JsonSerializerOptions? _options; |
| | | 17 | | |
| | | 18 | | /// <inheritdoc /> |
| | | 19 | | // ReSharper disable once ContextualLoggerProblem |
| | 3870 | 20 | | public VariableConverter(IWellKnownTypeRegistry wellKnownTypeRegistry, ILogger<VariableMapper> logger) |
| | | 21 | | { |
| | 3870 | 22 | | _mapper = new VariableMapper(wellKnownTypeRegistry, logger); |
| | 3870 | 23 | | } |
| | | 24 | | |
| | | 25 | | /// <inheritdoc /> |
| | | 26 | | public override Variable Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| | | 27 | | { |
| | 339 | 28 | | var newOptions = GetClonedOptions(options); |
| | 339 | 29 | | var model = JsonSerializer.Deserialize<VariableModel>(ref reader, newOptions)!; |
| | 339 | 30 | | var variable = _mapper.Map(model); |
| | | 31 | | |
| | 339 | 32 | | return variable; |
| | | 33 | | } |
| | | 34 | | |
| | | 35 | | /// <inheritdoc /> |
| | | 36 | | public override void Write(Utf8JsonWriter writer, Variable value, JsonSerializerOptions options) |
| | | 37 | | { |
| | 188 | 38 | | var model = _mapper.Map(value); |
| | 188 | 39 | | JsonSerializer.Serialize(writer, model, options); |
| | 188 | 40 | | } |
| | | 41 | | |
| | | 42 | | private JsonSerializerOptions GetClonedOptions(JsonSerializerOptions options) |
| | | 43 | | { |
| | 339 | 44 | | if(_options != null) |
| | 49 | 45 | | return _options; |
| | | 46 | | |
| | 290 | 47 | | var newOptions = new JsonSerializerOptions(options); |
| | 290 | 48 | | newOptions.Converters.Add(new JsonPrimitiveToStringConverter()); |
| | 290 | 49 | | _options = newOptions; |
| | 290 | 50 | | return newOptions; |
| | | 51 | | } |
| | | 52 | | } |