Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add error handling to json converters #611

Draft
wants to merge 1 commit into
base: dev
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 33 additions & 7 deletions Web/Edubase.Common/Formatting/Json/JsonTypeConverter.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using AutoMapper;
using AutoMapper;
using Newtonsoft.Json;
using System;
using System.ComponentModel;
Expand All @@ -15,29 +15,55 @@
=> destinationType == typeof(string);

public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
=> JsonConvert.DeserializeObject<T>(value?.ToString());
{
if (value == null) return default(T);

try
{
return JsonConvert.DeserializeObject<T>(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<T> : ITypeConverter<T, string>
{
string ITypeConverter<T, string>.Convert(T source, string destination, ResolutionContext context)
{
if (source == null) return null;

Check warning on line 48 in Web/Edubase.Common/Formatting/Json/JsonTypeConverter.cs

View workflow job for this annotation

GitHub Actions / build_and_test

Use a comparison to 'default(T)' instead or add a constraint to 'T' so that it can't be a value type. (https://rules.sonarsource.com/csharp/RSPEC-2955)
else return JsonConvert.SerializeObject(source);
}
}


public class FromJsonTypeConverter<T> : ITypeConverter<string, T>
{
T ITypeConverter<string, T>.Convert(string source, T destination, ResolutionContext context)
{
if (source.Clean() == null) return default(T);
else return JsonConvert.DeserializeObject<T>(source);
if (string.IsNullOrWhiteSpace(source)) return default(T);

try
{
return JsonConvert.DeserializeObject<T>(source);
}
catch (JsonReaderException)
{
return default(T);
}
}
}

}
Loading