< Summary

Information
Class: Elsa.Api.Client.Converters.TypeJsonConverter
Assembly: Elsa.Api.Client
File(s): /home/runner/work/elsa-core/elsa-core/src/clients/Elsa.Api.Client/Converters/TypeJsonConverter.cs
Line coverage
5%
Covered lines: 1
Uncovered lines: 16
Coverable lines: 17
Total lines: 56
Line coverage: 5.8%
Branch coverage
14%
Covered branches: 2
Total branches: 14
Branch coverage: 14.2%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
CanConvert(...)100%22100%
Read(...)0%620%
Write(...)0%110100%

File(s)

/home/runner/work/elsa-core/elsa-core/src/clients/Elsa.Api.Client/Converters/TypeJsonConverter.cs

#LineLine coverage
 1using System.Text.Json;
 2using System.Text.Json.Serialization;
 3using Elsa.Api.Client.Extensions;
 4using JetBrains.Annotations;
 5
 6namespace Elsa.Api.Client.Converters;
 7
 8/// <summary>
 9/// Converts <see cref="Type"/> objects to and from their assembly-qualified name.
 10/// </summary>
 11[UsedImplicitly]
 12public class TypeJsonConverter : JsonConverter<Type>
 13{
 14    /// <inheritdoc />
 15    public override bool CanConvert(Type typeToConvert)
 16    {
 30417        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    {
 023        var typeName = reader.GetString()!;
 24
 25        // Handle collection types.
 026        if (typeName.EndsWith("[]"))
 27        {
 028            var elementTypeName = typeName[..^"[]".Length];
 029            var elementType = Type.GetType(elementTypeName)!;
 030            return typeof(List<>).MakeGenericType(elementType);
 31        }
 32
 033        return Type.GetType(typeName);
 34    }
 35
 36    /// <inheritdoc />
 37    public override void Write(Utf8JsonWriter writer, Type value, JsonSerializerOptions options)
 38    {
 39        // Handle collection types.
 040        if (value is { IsGenericType: true, GenericTypeArguments.Length: 1 })
 41        {
 042            var elementType = value.GenericTypeArguments.First();
 043            var typedEnumerable = typeof(IEnumerable<>).MakeGenericType(elementType);
 44
 045            if (typedEnumerable.IsAssignableFrom(value))
 46            {
 047                var elementTypeName = value.GetSimpleAssemblyQualifiedName();
 048                JsonSerializer.Serialize(writer, $"{elementTypeName}[]", options);
 049                return;
 50            }
 51        }
 52
 053        var typeName = value.GetSimpleAssemblyQualifiedName();
 054        JsonSerializer.Serialize(writer, typeName, options);
 055    }
 56}