| | | 1 | | using System.Text.Json; |
| | | 2 | | using System.Text.Json.Serialization; |
| | | 3 | | using Elsa.Api.Client.Extensions; |
| | | 4 | | using JetBrains.Annotations; |
| | | 5 | | |
| | | 6 | | namespace Elsa.Api.Client.Converters; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Converts <see cref="Type"/> objects to and from their assembly-qualified name. |
| | | 10 | | /// </summary> |
| | | 11 | | [UsedImplicitly] |
| | | 12 | | public class TypeJsonConverter : JsonConverter<Type> |
| | | 13 | | { |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public override bool CanConvert(Type typeToConvert) |
| | | 16 | | { |
| | 304 | 17 | | return typeToConvert == typeof(Type) || typeToConvert.FullName == "System.RuntimeType"; |
| | | 18 | | } |
| | | 19 | | |
| | | 20 | | /// <inheritdoc /> |
| | | 21 | | public override Type? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| | | 22 | | { |
| | 0 | 23 | | var typeName = reader.GetString()!; |
| | | 24 | | |
| | | 25 | | // Handle collection types. |
| | 0 | 26 | | if (typeName.EndsWith("[]")) |
| | | 27 | | { |
| | 0 | 28 | | var elementTypeName = typeName[..^"[]".Length]; |
| | 0 | 29 | | var elementType = Type.GetType(elementTypeName)!; |
| | 0 | 30 | | return typeof(List<>).MakeGenericType(elementType); |
| | | 31 | | } |
| | | 32 | | |
| | 0 | 33 | | return Type.GetType(typeName); |
| | | 34 | | } |
| | | 35 | | |
| | | 36 | | /// <inheritdoc /> |
| | | 37 | | public override void Write(Utf8JsonWriter writer, Type value, JsonSerializerOptions options) |
| | | 38 | | { |
| | | 39 | | // Handle collection types. |
| | 0 | 40 | | if (value is { IsGenericType: true, GenericTypeArguments.Length: 1 }) |
| | | 41 | | { |
| | 0 | 42 | | var elementType = value.GenericTypeArguments.First(); |
| | 0 | 43 | | var typedEnumerable = typeof(IEnumerable<>).MakeGenericType(elementType); |
| | | 44 | | |
| | 0 | 45 | | if (typedEnumerable.IsAssignableFrom(value)) |
| | | 46 | | { |
| | 0 | 47 | | var elementTypeName = value.GetSimpleAssemblyQualifiedName(); |
| | 0 | 48 | | JsonSerializer.Serialize(writer, $"{elementTypeName}[]", options); |
| | 0 | 49 | | return; |
| | | 50 | | } |
| | | 51 | | } |
| | | 52 | | |
| | 0 | 53 | | var typeName = value.GetSimpleAssemblyQualifiedName(); |
| | 0 | 54 | | JsonSerializer.Serialize(writer, typeName, options); |
| | 0 | 55 | | } |
| | | 56 | | } |