| | | 1 | | using System.Text.Json; |
| | | 2 | | using System.Text.Json.Serialization; |
| | | 3 | | |
| | | 4 | | namespace 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> |
| | | 10 | | public class SafeDictionaryConverter : JsonConverter<IDictionary<string, object>> |
| | | 11 | | { |
| | | 12 | | /// <inheritdoc /> |
| | | 13 | | public override IDictionary<string, object> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOption |
| | | 14 | | { |
| | 0 | 15 | | 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 | | { |
| | 0 | 21 | | writer.WriteStartObject(); |
| | | 22 | | |
| | 0 | 23 | | foreach (var kvp in value) |
| | | 24 | | { |
| | 0 | 25 | | if (kvp.Value == null!) continue; // Skip null values |
| | | 26 | | |
| | 0 | 27 | | writer.WritePropertyName(kvp.Key); |
| | | 28 | | |
| | | 29 | | try |
| | | 30 | | { |
| | | 31 | | // Serialize the value to a temporary string. |
| | 0 | 32 | | var serializedValue = JsonSerializer.Serialize(kvp.Value, options); |
| | | 33 | | |
| | | 34 | | // Use the serialized string value to write to the main writer. |
| | 0 | 35 | | using var doc = JsonDocument.Parse(serializedValue); |
| | 0 | 36 | | doc.WriteTo(writer); |
| | 0 | 37 | | } |
| | 0 | 38 | | catch |
| | | 39 | | { |
| | | 40 | | // If serialization fails, write the fallback object. |
| | 0 | 41 | | writer.WriteStartObject(); |
| | 0 | 42 | | writer.WriteString("TypeName", kvp.Value.GetType().FullName); |
| | 0 | 43 | | writer.WriteEndObject(); |
| | 0 | 44 | | } |
| | | 45 | | } |
| | | 46 | | |
| | 0 | 47 | | writer.WriteEndObject(); |
| | 0 | 48 | | } |
| | | 49 | | } |