From d0d6e26a43fd3fa31a85d1848824a6f891bcdf41 Mon Sep 17 00:00:00 2001 From: syntaxonline-rewhitley <30848439+syntaxonline-rewhitley@users.noreply.github.com> Date: Fri, 23 Oct 2020 09:23:32 -0400 Subject: [PATCH] Add custom type serializer to manage json deserializer from database (#420) --- .../Converters/ExceptionConverter.cs | 28 +++++++++++++++++++ .../DbContexts/ElsaContext.cs | 3 ++ 2 files changed, 31 insertions(+) create mode 100644 src/core/Elsa.Core/Serialization/Converters/ExceptionConverter.cs diff --git a/src/core/Elsa.Core/Serialization/Converters/ExceptionConverter.cs b/src/core/Elsa.Core/Serialization/Converters/ExceptionConverter.cs new file mode 100644 index 000000000..1261f89c5 --- /dev/null +++ b/src/core/Elsa.Core/Serialization/Converters/ExceptionConverter.cs @@ -0,0 +1,28 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Text; + +namespace Elsa.Serialization.Converters +{ + public class ExceptionConverter : JsonConverter + { + + public override void WriteJson(JsonWriter writer, Exception value, JsonSerializer serializer) + { + throw new NotImplementedException("Unnecessary because CanRead is false. The type will skip the converter."); + } + public override bool CanWrite => false; + public override bool CanRead => true; + + public override Exception ReadJson(JsonReader reader, Type objectType, Exception existingValue, bool hasExistingValue, JsonSerializer serializer) + { + //reader will throw exception if not read to end + var jObject = JObject.Load(reader); + var ex = System.Text.Json.JsonSerializer.Deserialize(jObject.ToString()); + return ex; + + } + } +} diff --git a/src/persistence/Elsa.Persistence.EntityFrameworkCore/DbContexts/ElsaContext.cs b/src/persistence/Elsa.Persistence.EntityFrameworkCore/DbContexts/ElsaContext.cs index b422fbe3d..b83c37b1b 100644 --- a/src/persistence/Elsa.Persistence.EntityFrameworkCore/DbContexts/ElsaContext.cs +++ b/src/persistence/Elsa.Persistence.EntityFrameworkCore/DbContexts/ElsaContext.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using Elsa.Models; using Elsa.Persistence.EntityFrameworkCore.CustomSchema; using Elsa.Persistence.EntityFrameworkCore.Entities; +using Elsa.Serialization.Converters; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -29,6 +30,8 @@ namespace Elsa.Persistence.EntityFrameworkCore.DbContexts protected ElsaContext(DbContextOptions options) : base(options) { serializerSettings = new JsonSerializerSettings().ConfigureForNodaTime(DateTimeZoneProviders.Tzdb); + serializerSettings.Converters.Add(new ExceptionConverter()); + DbContextCustomSchema = options.GetDbContextCustomSchema(); }