Data and interface separation based on json.net for enum

Source: Internet
Author: User

In the daily work of the project process, has been very annoying enumeration values display problems. When adding, modifying, and deleting enumeration values, it is troublesome to modify the original Chinese expression of the interface. The corresponding extension for enum today, and the realization of Newtonsoft.json (json.net) jsonconverter personalization, separates the data from the interface, which is suitable for application development that relies on the Json data structure to transmit the information, for example: Web development.

1. First, implement the localization attribute tag

[AttributeUsage (Attributetargets.field)]      Public class Localizationattribute:attribute    {        public localizationattribute (string  showvalue)        {             = showvalue ;        }          Public string Get Set ; }    }

2. Implement Jsonconverter, change the original enum conversion result to {value:[int],showvalue:[string]}

  Public classEnumlocalizationconverter:jsonconverter { Public Override BOOLCanconvert (Type objectType) {returnObjecttype.isenum; }         Public Override ObjectReadjson (Jsonreader Reader, Type ObjectType,ObjectExistingvalue, Jsonserializer Serializer) {            Try            {                varValue = Serializer. Deserialize<enumlocalization>(reader); returnenum.parse (ObjectType, value.            Value.tostring ()); }            Catch            {            }                        returnEnum.parse (ObjectType, serializer. Deserialize (reader).        ToString ()); }         Public Override voidWritejson (Jsonwriter writer,Objectvalue, Jsonserializer serializer) {            varType =value.            GetType (); varFieldName =type.            Getenumname (value); if(FieldName! =NULL)            {                varLocalozation = type. GetField (FieldName). Getcustomattribute<localizationattribute>(); Serializer. Serialize (writer,New{value = value, Showvalue =localozation.            Showvalue}); }            Else{Serializer. Serialize (writer,NewEnumlocalization () {value = value, Showvalue =string.            Empty}); }        }    }
     Public class enumlocalization    {        publicobjectgetset;}          Public string Get Set ; }    }

3, implement the enum static extension function (get the text on the tag)

     Public Static classenumlocalizationextensions { Public Static stringTolocalizationstring ( ThisEnum _this) {            varType =_this.            GetType (); returnType. GetField (_this. ToString ()). Getcustomattribute<localizationattribute>().        Showvalue; }         Public Staticidictionary<int,string> Getlocalizations ( ThisEnum _this) {            varType =_this.            GetType (); vararr =type.            Getenumvalues (); Dictionary<int,string> dict =Newdictionary<int,string>(); foreach(intIincharr) {                varEnumvalue = Enum.parse (Type, i.tostring ()) asEnum; Dict.            ADD (i, enumvalue.tolocalizationstring ()); }            returndict; }    }

4. Use

    Public enumLogType {[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 classLog { Public intId {Get;Set; }  PublicUsermodel User {Get;Set; } [Jsonconverter (typeof(Enumlocalizationconverter))]  PublicLogType Type {Get;Set; }  PublicGuid UId {Get;Set; }  Public stringSummary {Get;Set; }  Public stringClientIP {Get;Set; }  Public stringServerName {Get;Set; }  PublicDateTime Createdt {Get;Set; } }

Data and interface separation based on json.net for enum

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.