| | | 1 | | using System.Reflection; |
| | | 2 | | using System.Text.Json; |
| | | 3 | | using System.Text.Json.Serialization; |
| | | 4 | | using Elsa.Extensions; |
| | | 5 | | using Elsa.Workflows.Attributes; |
| | | 6 | | |
| | | 7 | | namespace Elsa.Workflows.Serialization.Converters; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Serializes an object to JSON, excluding properties marked with <see cref="ExcludeFromHashAttribute"/>. |
| | | 11 | | /// </summary> |
| | | 12 | | public class ExcludeFromHashConverter : JsonConverter<object> |
| | | 13 | | { |
| | | 14 | | private JsonSerializerOptions? _options; |
| | | 15 | | |
| | | 16 | | /// <inheritdoc /> |
| | | 17 | | public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| | | 18 | | { |
| | 0 | 19 | | throw new NotSupportedException(); |
| | | 20 | | } |
| | | 21 | | |
| | | 22 | | /// <inheritdoc /> |
| | | 23 | | public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options) |
| | | 24 | | { |
| | 4314 | 25 | | writer.WriteStartObject(); |
| | 4314 | 26 | | var newOptions = GetClonedOptions(options); |
| | | 27 | | |
| | 116946 | 28 | | foreach (var property in value.GetType().GetProperties()) |
| | | 29 | | { |
| | 54159 | 30 | | var attribute = property.GetCustomAttribute<ExcludeFromHashAttribute>(); |
| | | 31 | | |
| | 54159 | 32 | | if (attribute != null) |
| | | 33 | | { |
| | | 34 | | continue; |
| | | 35 | | } |
| | | 36 | | |
| | 53064 | 37 | | writer.WritePropertyName(property.Name); |
| | 53064 | 38 | | JsonSerializer.Serialize(writer, property.GetValue(value), newOptions); |
| | | 39 | | } |
| | | 40 | | |
| | 4314 | 41 | | writer.WriteEndObject(); |
| | 4314 | 42 | | } |
| | | 43 | | |
| | | 44 | | private JsonSerializerOptions GetClonedOptions(JsonSerializerOptions options) |
| | | 45 | | { |
| | 4314 | 46 | | if(_options != null) |
| | 4300 | 47 | | return _options; |
| | | 48 | | |
| | 14 | 49 | | var newOptions = new JsonSerializerOptions(options); |
| | 42 | 50 | | newOptions.Converters.RemoveWhere(x => x is ExcludeFromHashConverterFactory); |
| | 14 | 51 | | return _options = newOptions; |
| | | 52 | | } |
| | | 53 | | } |
| | | 54 | | |
| | | 55 | | /// <summary> |
| | | 56 | | /// A factory for creating <see cref="ExcludeFromHashConverter"/> instances. |
| | | 57 | | /// </summary> |
| | | 58 | | public class ExcludeFromHashConverterFactory : JsonConverterFactory |
| | | 59 | | { |
| | | 60 | | /// <inheritdoc /> |
| | | 61 | | public override bool CanConvert(Type typeToConvert) => true; |
| | | 62 | | |
| | | 63 | | /// <inheritdoc /> |
| | | 64 | | public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) => new ExcludeFromH |
| | | 65 | | } |