| | | 1 | | using System.Text.Json; |
| | | 2 | | using System.Text.Json.Serialization; |
| | | 3 | | using Elsa.Extensions; |
| | | 4 | | using JetBrains.Annotations; |
| | | 5 | | using Elsa.Common.Serialization; |
| | | 6 | | |
| | | 7 | | namespace Elsa.Workflows.Serialization.Converters; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Serializes <see cref="Type"/> objects to a simple alias representing the type. |
| | | 11 | | /// Unregistered types are written as metadata-only aliases and intentionally deserialize to <see cref="Exception"/> ins |
| | | 12 | | /// </summary> |
| | | 13 | | [UsedImplicitly] |
| | | 14 | | public class TypeJsonConverter : JsonConverter<Type> |
| | | 15 | | { |
| | | 16 | | /// <summary> |
| | | 17 | | /// Prefix for unregistered type metadata that is not used for CLR type loading during deserialization. |
| | | 18 | | /// </summary> |
| | | 19 | | private const string UnregisteredTypeAliasPrefix = "UnregisteredClrType:"; |
| | | 20 | | private readonly ISerializationTypeRegistry _workflowJsonTypeRegistry; |
| | | 21 | | |
| | | 22 | | /// <inheritdoc /> |
| | 34291 | 23 | | public TypeJsonConverter(ISerializationTypeRegistry workflowJsonTypeRegistry) |
| | | 24 | | { |
| | 34291 | 25 | | _workflowJsonTypeRegistry = workflowJsonTypeRegistry; |
| | 34291 | 26 | | } |
| | | 27 | | |
| | | 28 | | /// <inheritdoc /> |
| | 6 | 29 | | public TypeJsonConverter() |
| | | 30 | | { |
| | 6 | 31 | | _workflowJsonTypeRegistry = SerializationTypeRegistry.CreateDefault(); |
| | 6 | 32 | | } |
| | | 33 | | |
| | | 34 | | /// <inheritdoc /> |
| | | 35 | | public override bool CanConvert(Type typeToConvert) |
| | | 36 | | { |
| | 733227 | 37 | | return typeToConvert == typeof(Type) || typeToConvert.FullName == "System.RuntimeType"; |
| | | 38 | | } |
| | | 39 | | |
| | | 40 | | /// <inheritdoc /> |
| | | 41 | | public override Type? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| | | 42 | | { |
| | 5056 | 43 | | var typeAlias = reader.GetString(); |
| | 5056 | 44 | | if (typeAlias?.StartsWith(UnregisteredTypeAliasPrefix, StringComparison.Ordinal) == true) |
| | 4 | 45 | | return typeof(Exception); |
| | | 46 | | |
| | 5052 | 47 | | return SerializationTypeResolver.ResolveType(_workflowJsonTypeRegistry, typeAlias); |
| | | 48 | | } |
| | | 49 | | |
| | | 50 | | /// <inheritdoc /> |
| | | 51 | | public override void Write(Utf8JsonWriter writer, Type value, JsonSerializerOptions options) |
| | | 52 | | { |
| | 12801 | 53 | | if (!SerializationTypeResolver.TryGetAlias(_workflowJsonTypeRegistry, value, out var typeAlias)) |
| | 4 | 54 | | typeAlias = $"{UnregisteredTypeAliasPrefix}{value.GetSimpleAssemblyQualifiedName()}"; |
| | | 55 | | |
| | 12801 | 56 | | writer.WriteStringValue(typeAlias); |
| | 12801 | 57 | | } |
| | | 58 | | } |