基于JSON.NET为Enum实现数据与界面分离

    在日常做项目过程中,一直很烦恼枚举值显示问题。当添加,修改,删除枚举值时,都要去修改界面原先的中文表述,很是麻烦。今天针对Enum做相应的扩展,并实现Newtonsoft.Json(JSON.NET)JsonConverter个性化定制,使数据与界面分离,此方法适用于依赖Json数据结构传输数据的应用开发,例如:web 开发。

1、首先,实现Localization属性标签

 [AttributeUsage(AttributeTargets.Field)]

    public class LocalizationAttribute : Attribute

    {

        public LocalizationAttribute(string showValue)

        {

            ShowValue = showValue;

        }



        public string ShowValue { get; set; }

    }

2、实现JsonConverter,将原先enum转换结果改成{Value:[int],ShowValue:[string]}

 public class EnumLocalizationConverter : JsonConverter

    {

        public override bool CanConvert(Type objectType)

        {

            return objectType.IsEnum;

        }



        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)

        {

            try

            {

                var value = serializer.Deserialize<EnumLocalization>(reader);

                return Enum.Parse(objectType, value.Value.ToString());

            }

            catch

            {

            }

            

            return Enum.Parse(objectType, serializer.Deserialize(reader).ToString());

        }



        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)

        {



            var type = value.GetType();

            var fieldName = type.GetEnumName(value);

            if (fieldName != null)

            {

                var localozation = type.GetField(fieldName).GetCustomAttribute<LocalizationAttribute>();

                serializer.Serialize(writer, new { Value = value, ShowValue = localozation.ShowValue });

            }

            else

            {

                serializer.Serialize(writer, new EnumLocalization() { Value = value, ShowValue = string.Empty });

            }

        }

    }
    public class EnumLocalization

    {

        public object Value { get; set; }

        public string ShowValue { get; set; }

    }

3、实现Enum静态扩展功能(获取标记上的文本)

    public static class EnumLocalizationExtensions

    {

        public static string ToLocalizationString(this Enum _this)

        {

            var type = _this.GetType();

            return type.GetField(_this.ToString()).GetCustomAttribute<LocalizationAttribute>().ShowValue;

        }



        public static IDictionary<int, string> GetLocalizations(this Enum _this)

        {

            var type = _this.GetType();

            var arr = type.GetEnumValues();

            Dictionary<int, string> dict = new Dictionary<int, string>();

            foreach (int i in arr)

            {

                var enumValue = Enum.Parse(type, i.ToString()) as Enum;

                dict.Add(i, enumValue.ToLocalizationString());

            }

            return dict;

        }

    }

4、使用

   public enum LogType

    {

        [Localization("登录")]

        Login = 1,

        [Localization("退出")]

        Exit = 2,

        [Localization("添加")]

        Add = 3,

        [Localization("删除")]

        Delete = 4,

        [Localization("修改")]

        Edit = 5,

        [Localization("测试")]

        Test = 6,

        [Localization("异常")]

        Exception = 7

    }
  public class Log

    {

        public int Id { get; set; }



        public UserModel User { get; set; }



        [JsonConverter(typeof(EnumLocalizationConverter))]

        public LogType Type { get; set; }



        public Guid UId { get; set; }



        public string Summary { get; set; }



        public string ClientIP { get; set; }



        public string ServerName { get; set; }



        public DateTime CreateDT { get; set; }

    }

 

你可能感兴趣的:(.net)