< Summary

Information
Class: Elsa.Workflows.Serialization.Converters.SafeDictionaryConverter
Assembly: Elsa.Workflows.Core
File(s): /home/runner/work/elsa-core/elsa-core/src/modules/Elsa.Workflows.Core/Serialization/Converters/SafeDictionaryConverter.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 16
Coverable lines: 16
Total lines: 49
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 4
Branch coverage: 0%
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(...)0%2040%

File(s)

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

#LineLine coverage
 1using System.Text.Json;
 2using System.Text.Json.Serialization;
 3
 4namespace Elsa.Workflows.Serialization.Converters;
 5
 6/// <summary>
 7/// A JSON converter that safely serializes a dictionary of objects, even if some of the objects are not serializable.
 8/// In that case, the converter will serialize a fallback object that contains the type name of the original object.
 9/// </summary>
 10public class SafeDictionaryConverter : JsonConverter<IDictionary<string, object>>
 11{
 12    /// <inheritdoc />
 13    public override IDictionary<string, object> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOption
 14    {
 015        return JsonSerializer.Deserialize<IDictionary<string, object>>(ref reader, options)!;
 16    }
 17
 18    /// <inheritdoc />
 19    public override void Write(Utf8JsonWriter writer, IDictionary<string, object> value, JsonSerializerOptions options)
 20    {
 021        writer.WriteStartObject();
 22
 023        foreach (var kvp in value)
 24        {
 025            if (kvp.Value == null!) continue; // Skip null values
 26
 027            writer.WritePropertyName(kvp.Key);
 28
 29            try
 30            {
 31                // Serialize the value to a temporary string.
 032                var serializedValue = JsonSerializer.Serialize(kvp.Value, options);
 33
 34                // Use the serialized string value to write to the main writer.
 035                using var doc = JsonDocument.Parse(serializedValue);
 036                doc.WriteTo(writer);
 037            }
 038            catch
 39            {
 40                // If serialization fails, write the fallback object.
 041                writer.WriteStartObject();
 042                writer.WriteString("TypeName", kvp.Value.GetType().FullName);
 043                writer.WriteEndObject();
 044            }
 45        }
 46
 047        writer.WriteEndObject();
 048    }
 49}