程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 基於JSON.NET為Enum實現數據與界面分離,json.netenum

基於JSON.NET為Enum實現數據與界面分離,json.netenum

編輯:C#入門知識

基於JSON.NET為Enum實現數據與界面分離,json.netenum


    在日常做項目過程中,一直很煩惱枚舉值顯示問題。當添加,修改,刪除枚舉值時,都要去修改界面原先的中文表述,很是麻煩。今天針對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; }
    }

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved