From d6b68aab67d5705b71b97ffc61335dc39cd29978 Mon Sep 17 00:00:00 2001 From: Barry GIBNEY Date: Thu, 21 Nov 2024 13:57:46 +0000 Subject: [PATCH] Add error handling to json converters --- .../Formatting/Json/JsonTypeConverter.cs | 40 +++++++++++++++---- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/Web/Edubase.Common/Formatting/Json/JsonTypeConverter.cs b/Web/Edubase.Common/Formatting/Json/JsonTypeConverter.cs index 4e01cd5e0..69b5731ef 100644 --- a/Web/Edubase.Common/Formatting/Json/JsonTypeConverter.cs +++ b/Web/Edubase.Common/Formatting/Json/JsonTypeConverter.cs @@ -1,4 +1,4 @@ -using AutoMapper; +using AutoMapper; using Newtonsoft.Json; using System; using System.ComponentModel; @@ -15,10 +15,30 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati => destinationType == typeof(string); public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) - => JsonConvert.DeserializeObject(value?.ToString()); + { + if (value == null) return default(T); + + try + { + return JsonConvert.DeserializeObject(value.ToString()); + } + catch (JsonReaderException) + { + return default(T); + } + } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) - => JsonConvert.SerializeObject(value); + { + try + { + return JsonConvert.SerializeObject(value); + } + catch (JsonReaderException) + { + return string.Empty; + } + } } public class ToJsonTypeConverter : ITypeConverter @@ -30,14 +50,20 @@ string ITypeConverter.Convert(T source, string destination, Resolutio } } - public class FromJsonTypeConverter : ITypeConverter { T ITypeConverter.Convert(string source, T destination, ResolutionContext context) { - if (source.Clean() == null) return default(T); - else return JsonConvert.DeserializeObject(source); + if (string.IsNullOrWhiteSpace(source)) return default(T); + + try + { + return JsonConvert.DeserializeObject(source); + } + catch (JsonReaderException) + { + return default(T); + } } } - }