Extension methods for JSON serialization and deserialization

Source: Internet
Author: User
Tags tojson

this+ type name + variable name, a new feature called "extension method" after. NET 3.0.

The int type variable can call the ToString () method to convert the int type variable to a string variable, and if you need to change the form of the transformation, such as converting an int type variable to a string of the specified format, and this method invocation is very frequent, you can write an extension method. Extension methods can "add" methods to existing types without having to create new derived types, recompile, or otherwise modify the original type. An extension method is a special static method, but it can be called just like an instance method on an extended type.

For example, the following code:

namespace extensionmethods{public    static class MyExtensions    {public        static int zzyhost (this String str) c3/>{                     return 0;}}   }

In other classes, only the using Extensionmethods is required to introduce the namespace, and all string objects have the Zzyhost () method without rewriting a string class, which is called directly when used:

string s = "Hello zzyhost"; int i = S.zzyhost ();

When you do a Web project, you often go to JSON, so you can write the transformation method as an extension method and call it directly at the time of conversion.

Extension methods:

/********************************************************************************** title:serializerutil** author:dwx** e-mail [email protected]** date:2017/5/12 9:12:34** clr:4.0.30319.34209** Copyright : Copyright (c) 2017** company:gdwinning * * Description:json serialization extension method ************************************************* ********************************/usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Runtime.Serialization.Json;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Runtime.Serialization;namespaceBLL. tool{/// <summary>    ///extension methods, JSON serialization/// </summary>     Public Static classJsonserializerutil {/// <summary>        ///JSON string deserialization/// </summary>        /// <typeparam name= "T" ></typeparam>        /// <param name= "Jsonstr" ></param>        /// <returns></returns>         Public StaticT fromjson<t> ( This stringjsonstr) {            Try{DataContractJsonSerializer Seri=NewDataContractJsonSerializer (typeof(T)); using(MemoryStream memory =NewMemoryStream (Encoding.UTF8.GetBytes (JSONSTR))) {T Jsonobj=(T) Seri.                    ReadObject (memory); returnJsonobj; }            }            Catch            {                return default(T);//returns NULL if there is an exception            }        }        /// <summary>        ///JSON serialization/// </summary>        /// <param name= "item" ></param>        /// <returns></returns>         Public Static stringToJson ( This ObjectItem) {            Try{DataContractJsonSerializer Serializer=NewDataContractJsonSerializer (item.                GetType ()); using(MemoryStream ms =NewMemoryStream ()) {Serializer.                    WriteObject (MS, item); StringBuilder SB=NewStringBuilder (); Sb. Append (Encoding.UTF8.GetString (Ms.                    ToArray ())); returnsb.                ToString (); }            }            Catch(Exception ex) {return "Exception Information:"+Ex.            Message; }        }    }}

Example of calling an extension method:

Result res=new result (); String data=null;//object serializes data = Res. ToJson ();//json string deserialization result newres=new result (); Newres=data. Fromjson<result> ();

  

Extension methods for JSON serialization and deserialization

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.