| | | 1 | | using System.Text.Json; |
| | | 2 | | using System.Text.Json.Serialization; |
| | | 3 | | using Elsa.Extensions; |
| | | 4 | | |
| | | 5 | | namespace 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> |
| | | 11 | | public 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 | | { |
| | 0 | 18 | | var newOptions = GetClonedOptions(options); |
| | 0 | 19 | | 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 | | { |
| | 2142 | 27 | | var newOptions = GetClonedOptions(options); |
| | | 28 | | |
| | | 29 | | // Serialize the value to a temporary string. |
| | 2142 | 30 | | var serializedValue = JsonSerializer.Serialize(value, newOptions); |
| | | 31 | | |
| | | 32 | | // Use the serialized string value to write to the main writer. |
| | 2142 | 33 | | using var doc = JsonDocument.Parse(serializedValue); |
| | 2142 | 34 | | doc.WriteTo(writer); |
| | 2142 | 35 | | } |
| | 0 | 36 | | catch |
| | | 37 | | { |
| | | 38 | | // If serialization fails, write the fallback object. |
| | 0 | 39 | | writer.WriteStartObject(); |
| | 0 | 40 | | writer.WriteString("TypeName", value.GetType().FullName); |
| | 0 | 41 | | writer.WriteEndObject(); |
| | 0 | 42 | | } |
| | 2142 | 43 | | } |
| | | 44 | | |
| | | 45 | | private JsonSerializerOptions GetClonedOptions(JsonSerializerOptions options) |
| | | 46 | | { |
| | 2142 | 47 | | if(_options != null) |
| | 2028 | 48 | | return _options; |
| | | 49 | | |
| | 114 | 50 | | var newOptions = new JsonSerializerOptions(options); |
| | 1597 | 51 | | newOptions.Converters.RemoveWhere(x => x is SafeValueConverterFactory); |
| | 114 | 52 | | _options = newOptions; |
| | 114 | 53 | | return newOptions; |
| | | 54 | | } |
| | | 55 | | } |