Json serialization and deserialization tool using Json.NET (Newtonsoft.json) as ASP.

Source: Internet
Author: User

The default JSON serialization for the ASP. NET MVC uses Microsoft's own JavaScriptSerializer. Low performance does not say, the most unbearable is the dictionary<,> and Hashtable type actually corresponds to the JSON is [{"Key": "A", "Value": 1}] Instead of {"A": 1}. Really wonderful home, with the front end can not be integrated!

Decide or use json.net to do it! Looked up all kinds of information, the online code is either too complex, or can not be fully realized. Again in Ilspy analysis of MVC source code, and then debugging for half a day, finally have a preliminary solution:

1, deserialization, first establish the following class:

1 usingSystem;2 usingSystem.Globalization;3 usingSystem.IO;4 usingSYSTEM.WEB.MVC;5 usingNewtonsoft.Json.Linq;6 7 namespaceHZ8 {9      Public classjsonnetvalueproviderfactory:valueproviderfactoryTen     { One          Public Overrideivalueprovider Getvalueprovider (controllercontext ctlcontext) A         { -             //if (!controllercontext.httpcontext.request.contenttype. -             //StartsWith ("Application/json", StringComparison.OrdinalIgnoreCase)) the             //{ -             //return null; -             //} -  +             varReader =NewStreamReader (ctlContext.HttpContext.Request.InputStream); -Reader. Basestream.position =0; +             varJSON =Reader. ReadToEnd (); A             if(string. IsNullOrEmpty (JSON)) at                 return NULL; -  -             varJtoken = json. StartsWith ("[")  -? Jarray.parse (JSON) asJcontainer -: Jobject.parse (JSON) asJcontainer; -             return NewJsonnetvalueprovider (jtoken); in         } -     } to  +      Public classJsonnetvalueprovider:ivalueprovider -     { the         PrivateJcontainer _jvalue; *  $          PublicJsonnetvalueprovider (Jcontainer jval)Panax Notoginseng         { -_jvalue =Jval; the         } +  A          Public BOOLContainsprefix (stringprefix) the         { +             return true; -         } $  $          PublicValueproviderresult GetValue (stringkey) -         { -             varJtoken =_jvalue.selecttoken (key); the             if(Jtoken = =NULL) -             {WuyiJtoken =_jvalue; the             } -             return NewJsonnetvalueproviderresult (Jtoken, Key,NULL); Wu         } -     } About  $      Public classJsonnetvalueproviderresult:valueproviderresult -     { -         PrivateJtoken _jtoken; -          PublicJsonnetvalueproviderresult (Jtoken Valueraw,stringkey, CultureInfo info) A         { +_jtoken =Valueraw; the         } -          Public Override ObjectConvertTo (Type type, CultureInfo culture) $         { the             return_jtoken?. Toobject (type); the         } the     } the  -      Public classJsonnetmodelbinder:defaultmodelbinder in     { the          Public Override ObjectBindmodel (ControllerContext controllercontext, Modelbindingcontext BindingContext) the         { About             varProvider =BindingContext.ValueProvider.GetValue (bindingcontext.modelname); the             returnprovider. ConvertTo (bindingcontext.modeltype); the         } the     } +}

2, and then Application_Start or router initialization, call the following code:

            // Reset JSON serialization, using Json.NET instead             ValueProviderFactories.Factories.Remove (valueproviderfactories.factories.                OfType<JsonValueProviderFactory>(). FirstOrDefault ());            VALUEPROVIDERFACTORIES.FACTORIES.ADD (new  jsonnetvalueproviderfactory ());             // Reset The binder of the system so that the dictionary can be normal JSON            New Jsonnetmodelbinder ();

The principle is basically to replace the system's own valueproviderfactory and Defaultmodelbinder, and then use your own class to invoke the Json.NET implementation.

3, the process of serialization is relatively simple, the establishment of a Jsonnetresult class, and then the MVC method returns this type can be.

  Public classJsonnetresult:jsonresult { PublicJsonserializersettings Settings {Get;Private Set; }  Public Override voidExecuteresult (ControllerContext context) {//if (context = = null)//throw new ArgumentNullException ("context"); //if (this. Jsonrequestbehavior = = Jsonrequestbehavior.denyget && string. Equals (context. HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))//throw new InvalidOperationException ("JSON GET is not allowed");httpresponsebase Response=context.            Httpcontext.response; Response. ContentType=string. IsNullOrEmpty ( This. ContentType)?"Application/json": This.            ContentType; if( This. ContentEncoding! =NULL) Response. ContentEncoding= This.            ContentEncoding; if( This. Data = =NULL)                return; varScriptserializer = Jsonserializer.create ( This.            Settings); using(varSW =NewStringWriter ()) {scriptserializer.serialize (SW, This.                Data); Response. Write (SW.            ToString ()); }        }    }

Json serialization and deserialization tool using Json.NET (Newtonsoft.json) as ASP.

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.