码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-05-22 15:08:07      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

    在日常做项目过程中,一直很烦恼枚举值显示问题。当添加,修改,删除枚举值时,都要去修改界面原先的中文表述,很是麻烦。今天针对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; }
    }

 

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

标签:

原文地址:http://www.cnblogs.com/akong/p/4522244.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!