< Summary

Information
Class: Elsa.Workflows.Serialization.Converters.SafeValueConverter
Assembly: Elsa.Workflows.Core
File(s): /home/runner/work/elsa-core/elsa-core/src/modules/Elsa.Workflows.Core/Serialization/Converters/SafeValueConverter.cs
Line coverage
63%
Covered lines: 12
Uncovered lines: 7
Coverable lines: 19
Total lines: 55
Line coverage: 63.1%
Branch coverage
100%
Covered branches: 2
Total branches: 2
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
Read(...)100%210%
Write(...)100%1154.54%
GetClonedOptions(...)100%22100%

File(s)

/home/runner/work/elsa-core/elsa-core/src/modules/Elsa.Workflows.Core/Serialization/Converters/SafeValueConverter.cs

#LineLine coverage
 1using System.Text.Json;
 2using System.Text.Json.Serialization;
 3using Elsa.Extensions;
 4
 5namespace Elsa.Workflows.Serialization.Converters;
 6
 7/// <summary>
 8/// A JSON converter that safely serializes a value, even if it's not serializable.
 9/// In that case, the converter will serialize a fallback object that contains the type name of the original object.
 10/// </summary>
 11public class SafeValueConverter : JsonConverter<object>
 12{
 13    private JsonSerializerOptions? _options;
 14
 15    /// <inheritdoc />
 16    public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
 17    {
 018        var newOptions = GetClonedOptions(options);
 019        return JsonSerializer.Deserialize(ref reader, typeToConvert, newOptions)!;
 20    }
 21
 22    /// <inheritdoc />
 23    public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
 24    {
 25        try
 26        {
 214227            var newOptions = GetClonedOptions(options);
 28
 29            // Serialize the value to a temporary string.
 214230            var serializedValue = JsonSerializer.Serialize(value, newOptions);
 31
 32            // Use the serialized string value to write to the main writer.
 214233            using var doc = JsonDocument.Parse(serializedValue);
 214234            doc.WriteTo(writer);
 214235        }
 036        catch
 37        {
 38            // If serialization fails, write the fallback object.
 039            writer.WriteStartObject();
 040            writer.WriteString("TypeName", value.GetType().FullName);
 041            writer.WriteEndObject();
 042        }
 214243    }
 44
 45    private JsonSerializerOptions GetClonedOptions(JsonSerializerOptions options)
 46    {
 214247        if(_options != null)
 202848            return _options;
 49
 11450        var newOptions = new JsonSerializerOptions(options);
 159751        newOptions.Converters.RemoveWhere(x => x is SafeValueConverterFactory);
 11452        _options = newOptions;
 11453        return newOptions;
 54    }
 55}