MVC uses Newtonsoft.json to deserialize JSON data

Source: Internet
Author: User
Tags httpcontext

The JSON return serialization tool that is used by default in MVC is Jsonvalueproviderfactory,jsonvalueproviderfactory inherited from the Valueproviderfactory abstract class. The serialized class library used by Jsonvalueproviderfactory is System.Web.Script.Serialization. Now let's write our own square sequence tool, using the Newtonsoft.json serialization and deserialization tool.

The Jsonvalueproviderfactory code is specific as follows:

Using system;using system.collections;using system.collections.generic;using system.dynamic;using System.globalization;using system.io;using system.web.mvc;using newtonsoft.json;using Newtonsoft.Json.Converters; Namespace aft.build.mvcweb.common{public class Jsonnetvalueproviderfactory:valueproviderfactory {public O Verride ivalueprovider Getvalueprovider (controllercontext controllercontext) {//First make sure we hav e A valid context if (ControllerContext = = null) throw new ArgumentNullException ("Controllercont            Ext "); Now make sure we is dealing with a JSON request if (!controllercontext.httpcontext.request.contenttype.star            Tswith ("Application/json", stringcomparison.ordinalignorecase)) return null; Get a generic stream reader (get reader for the HTTP stream) var streamReader = new StreamReader (CONTROLLERC Ontext.            HttpContext.Request.InputStream); ConVert Stream Reader to a JSON Text reader var jsonreader = new JsonTextReader (StreamReader);            Tell JSON to read if (!jsonreader.read ()) return null;            Make a new Json serializer var jsonserializer = new Jsonserializer (); Add the Dyamic object Converter to our serializer JsonSerializer.Converters.Add (new Expandoobjectconverter ()            );            Use Json.NET to deserialize object to a dynamic (expando) object Object Jsonobject;                If we start with a "[", treat the As an array if (Jsonreader.tokentype = = Jsontoken.startarray)            Jsonobject = jsonserializer.deserialize<list<expandoobject>> (Jsonreader);            else Jsonobject = jsonserializer.deserialize<expandoobject> (Jsonreader); Create a backing store to hold all properties for this deserialization var backingstore = new dictionary< STring, object> (stringcomparer.ordinalignorecase);            Add all properties to this backing store Addtobackingstore (Backingstore, String.Empty, Jsonobject); Return the object in a dictionary value provider so the MVC understands it return new Dictionaryvaluepro        Vider<object> (Backingstore, CultureInfo.CurrentCulture);         } private static void Addtobackingstore (Dictionary<string, object> backingstore, string prefix, object value)            {var d = value as Idictionary<string, object>; if (d! = null) {foreach (var entry in D) {Addtobackingstore ( Backingstore, Makepropertykey (prefix, entry. Key), entry.                Value);            } return;            } var L = value as IList; if (l! = null) {for (int i = 0; i < L.count; i++) {Addtob AckingstorE (Backingstore, makearraykey (prefix, i), l[i]);            } return;        }//Primitive backingstore[prefix] = value; } private static string Makearraykey (string prefix, int index) {return prefix + "[" + Index.        ToString (CultureInfo.InvariantCulture) + "]"; } private static string Makepropertykey (string prefix, String propertyname) {return (STRING.ISNU Llorempty (prefix))?        Propertyname:prefix + "." + PropertyName; }    }}

Then register the jsonvalueproviderfactory with the global JSON data for deserialization:

Add the following two lines of code to the Global.asax file Application_Start method:

ValueProviderFactories.Factories.Remove (valueproviderfactories.factories.oftype<jsonvalueproviderfactory > (). FirstOrDefault ());            VALUEPROVIDERFACTORIES.FACTORIES.ADD (New Jsonnetvalueproviderfactory ());
The first sentence is to remove the original jsonvalueproviderfactory deserialization, and the second sentence is to add your own deserialization tool.

Summary and Precautions:

1.MVC client data-to-server segment data type conversions are registered through Valueproviderfactories.

2. Remember that the data packets that are uploaded to the server segment via Ajax in MVC must be content-type:Application/json, Or we won't use our own jsonnetvalueproviderfactory. Deserialization tool


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.