aspnetcore.3.0.typeConverter.mustache Maven / Gradle / Ivy
{{>partial_header}}
using System;
using System.ComponentModel;
using System.Globalization;
{{#useNewtonsoft}}
using Newtonsoft.Json;
{{/useNewtonsoft}}
{{^useNewtonsoft}}
using System.Text.Json;
{{/useNewtonsoft}}
namespace {{packageName}}.Converters
{
///
/// Custom string to enum converter
///
public class CustomEnumConverter : TypeConverter
{
///
/// Determine if we can convert a type to an enum
///
///
///
///
public override bool CanConvertFrom(ITypeDescriptorContext{{#nullableReferenceTypes}}?{{/nullableReferenceTypes}} context, Type sourceType)
{
return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
}
///
/// Convert from a type value to an enum
///
///
///
///
///
public override object{{#nullableReferenceTypes}}?{{/nullableReferenceTypes}} ConvertFrom(ITypeDescriptorContext{{#nullableReferenceTypes}}?{{/nullableReferenceTypes}} context, CultureInfo{{#nullableReferenceTypes}}?{{/nullableReferenceTypes}} culture, object value)
{
var s = value as string;
if (string.IsNullOrEmpty(s))
{
return null;
}
return {{#useNewtonsoft}}JsonConvert.DeserializeObject{{/useNewtonsoft}}{{^useNewtonsoft}}JsonSerializer.Deserialize{{/useNewtonsoft}}(@"""" + value + @"""");
}
}
}