Data and interface separation for Enum Based on JSON. NET, json. netenum

Source: Internet
Author: User

Data and interface separation for Enum Based on JSON. NET, json. netenum

During the daily project process, I have been worried about the problem of displaying enumeration values. When you add, modify, or delete enumeration values, you must modify the original Chinese expression on the interface, which is very troublesome. Today, we have made corresponding extensions for Enum and implemented Newtonsoft. json (JSON.. NET) JsonConverter is customized to separate the data from the interface. This method is applicable to application development that relies on the Json data structure to transmit data, for example, web development.

1. First, implement Localization attribute labels

 [AttributeUsage(AttributeTargets.Field)]    public class LocalizationAttribute : Attribute    {        public LocalizationAttribute(string showValue)        {            ShowValue = showValue;        }        public string ShowValue { get; set; }    }

2. Implement JsonConverter and change the original enum Conversion Result to {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. Implement the static Extension function of Enum (obtain the marked text)

    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. Use

Public enum LogType {[Localization ("Login")] Login = 1, [Localization ("Exit")] Exit = 2, [Localization ("Add")] Add = 3, [Localization ("Delete")] Delete = 4, [Localization ("modify")] Edit = 5, [Localization ("Test")] Test = 6, [Localization ("Exception")] 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; }    }

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.