All Downloads are FREE. Search and download functionalities are using the official Maven repository.

aspnetcore.3.0.typeConverter.mustache Maven / Gradle / Ivy

There is a newer version: 7.6.0
Show newest version
{{>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 + @"""");
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy