| | | 1 | | using System.Text.Json; |
| | | 2 | | using System.Text.Json.Serialization; |
| | | 3 | | using Elsa.Expressions.Contracts; |
| | | 4 | | using Elsa.Expressions.Extensions; |
| | | 5 | | using Elsa.Workflows.Memory; |
| | | 6 | | using Elsa.Workflows.Models; |
| | | 7 | | |
| | | 8 | | namespace Elsa.Workflows.Serialization.Converters; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// Serializes <see cref="Input"/> objects. |
| | | 12 | | /// </summary> |
| | | 13 | | public class OutputJsonConverter<T> : JsonConverter<Output<T>?> |
| | | 14 | | { |
| | | 15 | | private readonly IWellKnownTypeRegistry _wellKnownTypeRegistry; |
| | | 16 | | |
| | | 17 | | /// <inheritdoc /> |
| | 1522 | 18 | | public OutputJsonConverter(IWellKnownTypeRegistry wellKnownTypeRegistry) |
| | | 19 | | { |
| | 1522 | 20 | | _wellKnownTypeRegistry = wellKnownTypeRegistry; |
| | 1522 | 21 | | } |
| | | 22 | | |
| | | 23 | | /// <inheritdoc /> |
| | 0 | 24 | | public override bool CanConvert(Type typeToConvert) => typeof(Output).IsAssignableFrom(typeToConvert); |
| | | 25 | | |
| | | 26 | | /// <inheritdoc /> |
| | | 27 | | public override Output<T>? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| | | 28 | | { |
| | 0 | 29 | | if (!JsonDocument.TryParseValue(ref reader, out var doc)) |
| | 0 | 30 | | return null; |
| | | 31 | | |
| | 0 | 32 | | if (!doc.RootElement.TryGetProperty("typeName", out _)) |
| | 0 | 33 | | return null; |
| | | 34 | | |
| | 0 | 35 | | var memoryReferenceElement = doc.RootElement.GetProperty("memoryReference"); |
| | | 36 | | |
| | 0 | 37 | | if (!memoryReferenceElement.TryGetProperty("id", out var memoryReferenceIdElement)) |
| | 0 | 38 | | return default; |
| | | 39 | | |
| | 0 | 40 | | var variable = new Variable |
| | 0 | 41 | | { |
| | 0 | 42 | | Id = memoryReferenceIdElement.GetString()! |
| | 0 | 43 | | }; |
| | 0 | 44 | | variable.Name = variable.Id; |
| | | 45 | | |
| | 0 | 46 | | return (Output<T>)Activator.CreateInstance(typeof(Output<T>), variable)!; |
| | | 47 | | } |
| | | 48 | | |
| | | 49 | | /// <inheritdoc /> |
| | | 50 | | public override void Write(Utf8JsonWriter writer, Output<T>? value, JsonSerializerOptions options) |
| | | 51 | | { |
| | 40 | 52 | | var valueType = typeof(T); |
| | 40 | 53 | | var valueTypeAlias = _wellKnownTypeRegistry.GetAliasOrDefault(valueType); |
| | | 54 | | |
| | 40 | 55 | | var model = new |
| | 40 | 56 | | { |
| | 40 | 57 | | TypeName = valueTypeAlias, |
| | 40 | 58 | | MemoryReference = value == null ? null : new |
| | 40 | 59 | | { |
| | 40 | 60 | | Id = value.MemoryBlockReference().Id |
| | 40 | 61 | | } |
| | 40 | 62 | | }; |
| | | 63 | | |
| | 40 | 64 | | JsonSerializer.Serialize(writer, model, options); |
| | 40 | 65 | | } |
| | | 66 | | } |