Newtonsoft.json advanced Usage Enumeration Chinese escape

Source: Internet
Author: User

The recent two articles on "Newtonsoft.json Advanced usage" in the blog Park have been commented on by many people, once logged in to the headline recommendation.

Today I will not repeat the advanced usage of some of the newtonsoft.json mentioned in the Plume blog post. If you want to know, go straight to see.

Newtonsoft.json advanced usage and further discussion on Newtonsoft.json advanced usage

I'm mainly talking about the use of the plume not mentioned--enumeration Chinese escape

enumeration value serialization problem (excerpt from flame tail iteration)
PublicEnumNotifytype {///<summary>///Emil Send///</summary> mail=0,///<summary> //////</summary> sms= 1 public class Testenmu {////// message send type ///</summary>  Public Notifytype Type {get; setnew Testenmu ());       

Output: Now retrofit, Output "Type": "Mail"

    Class Testenmu    {        <summary>        //</summary> [Jsonconverter (typeof set;}}      

The other is the same, with the type attribute added Jsonconverter (typeof (Stringenumconverter)) to convert the enumeration value to the corresponding string, The Stringenumconverter is the Newtonsoft.json built-in conversion type, which results in the final output

Thinking

Here Stringenumconverter does solve a lot of problems for us, from the enumeration value type to the name. If we were English, it would be nice to come here Newtonsoft.json brought converter has solved all the problems for us.

Who call us Chinese, to the enumeration to turn mail still very uncomfortable.

If we can turn the enumeration into "e-mail" to meet our Chinese habits.

{     "Type":" e-mail "}
Chinese serialization of enumeration values

First, we'll start by transforming our enumeration type, based on the above target.

 Public enumnotifytype{/// <summary>            ///e-Mail/// </summary>[Description ("e-Mail")] Mail=0,            /// <summary>            ///Mobile SMS/// </summary>[Description ("Mobile SMS")]
SMS=1
}

Next we customize a Enumjsonconvert class, considering that our enumerations might pass in different types, we use generics here

  Public classEnumjsonconvert<t>:jsonconverterwhereT:struct, IConvertible { Public voidEnumconverter () {if(!typeof(T). Isenum) {Throw NewArgumentException ("T must be an enumeration type"); }        }         Public Override ObjectReadjson (Jsonreader Reader, Type ObjectType,ObjectExistingvalue, Jsonserializer Serializer) {            if(Reader. Tokentype = =jsontoken.null) {return NULL; }            Try            {                returnReader.            Value.tostring (); }            Catch(Exception ex) {Throw NewException (string. Format ("The value {0} of the enumeration {1} cannot be converted to JSON format.", reader.            Value, ObjectType)); }                   }        /// <summary>        ///determine if the type is bool/// </summary>        /// <param name= "ObjectType" >type</param>        /// <returns>can be converted to type bool</returns>         Public Override BOOLCanconvert (Type objectType) {return true; }         Public BOOLIsnullabletype (Type t) {if(T = =NULL)            {                Throw NewArgumentNullException (nameof (t)); }            returnT.basetype! =NULL&& (T.basetype.fullname = ="System.ValueType"&& t.getgenerictypedefinition () = =typeof(nullable<>)); }         Public Override voidWritejson (Jsonwriter writer,Objectvalue, Jsonserializer serializer) {            if(Value = =NULL) {writer.                Writenull (); return; }                stringBValue =value.                ToString (); intIsNo; if(int. TryParse (BValue, outisNo)) {BValue= Getenumdescription (typeof(T), isNo); }                Else{BValue= Getenumdescription (typeof(T), value.                ToString ()); } writer.        WriteValue (BValue); }        /// <summary>        ///Get Enumeration Description/// </summary>        /// <param name= "type" >Enum Type</param>        /// <param name= "value" >Enumeration Name</param>        /// <returns></returns>        Private  stringGetenumdescription (Type type,stringvalue) {            Try{FieldInfo field=type.                GetField (value); if(Field = =NULL)                {                    return ""; }                vardesc = attribute.getcustomattribute (field,typeof(DescriptionAttribute)) asDescriptionAttribute; if(Desc! =NULL)returnDesc.                Description; return ""; }            Catch            {                return ""; }        }        /// <summary>        ///Get Enumeration Description/// </summary>        /// <param name= "type" >Enum Type</param>        /// <param name= "value" >Enumeration Hasecode</param>        /// <returns></returns>        Private  stringGetenumdescription (Type type,intvalue) {            Try{FieldInfo field=type.                GetField (Enum.getname (type, value)); if(Field = =NULL)                {                    return ""; }                vardesc = attribute.getcustomattribute (field,typeof(DescriptionAttribute)) asDescriptionAttribute; if(Desc! =NULL)returnDesc.                Description; return ""; }            Catch            {                return ""; }        }    }

Our custom JsonConvert has been implemented here. Start using it.

We define a class of MyClass

 Public class MyClass        {            publicstringgetset;}            [Jsonconverter (typeof (Enumjsonconvert<notifytype>))]   This is our special place             . Public intgetset;}        }

Let's write a test to see if it's right:

The results are as follows:

We achieved our initial goal, in general our database to the value type that holds the enumeration, such as the 0,1,2,3 here .... We usually need to display the front-end language, such as the e-mail here, mobile phone messages ... Summarize

In fact, the customization here implements a JSON custom type conversion. Enumerates the Chinese escapes with reflection using the description attribute of the enumeration. In fact, this kind of escape in our usual development process is often seen. The use of JsonConvert can bring us some decoupling.

Omit if Esleif and other judgments.

From the top to the bottom, the main only to explain a problem, the lines of language are a lot of not rigorous. Not many knowledge methods are the same, the code is all affixed, I hope to help you. Thank you.

Colleagues once again thanked the flame tail for sharing. Thank you! , but also hope to be the same as you are recommended by everyone. Thank you.

Newtonsoft.json advanced Usage Enumeration Chinese escape

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.