Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to make JSON.NET as the default JSON serializer in ASP.NET MVC

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 6.22k
    Comment on it

    "Making JSON.NET as the default JSON serializer in ASP.NET MVC"

        The default JSON serializer in Asp.Net MVC is JavascriptSerializer.   In this article I will explain how to replace the JavascriptSerializer for serializing outgoing data by Json.NET.

    Getting Started:

    Step 1: Create an abstract class (Say "BaseController") as follows (I have made it inside a Service folder):

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web;
    using System.Web.Mvc;
    
    namespace MultipleSubmit.Service
    {
        public abstract class BaseController : Controller
        {
            protected override JsonResult Json(object data, string contentType,
                Encoding contentEncoding, JsonRequestBehavior behavior)
            {
                return new JsonNetResult
                {
                    Data = data,
                    ContentType = contentType,
                    ContentEncoding = contentEncoding,
                    JsonRequestBehavior = behavior
                };
            }
        }
    }
    

    This class has to be inherited by the Controller which wants to use JSON.NET as serializer. Now we will create a class JsonNetResult as you can see in the above code.

    Step 2: Create a class JsonNetResult and extend the JsonResult class. What we have to do is that we have to override the ExecuteResult method of the JsonResult class.This gives us opportunity to select how we want to serialize the Json data and then we can use JsonSerializer from Json. The JsonNetResult class is as follows:

    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace MultipleSubmit.Service
    {
        public class JsonNetResult : JsonResult
        {
            public JsonNetResult()
            {
                Settings = new JsonSerializerSettings
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Error
                };
            }
    
            public JsonSerializerSettings Settings { get; private set; }
    
            public override void ExecuteResult(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;
    
                var scriptSerializer = JsonSerializer.Create(this.Settings);
    
                using (var sw = new StringWriter())
                {
                    scriptSerializer.Serialize(sw, this.Data);
                    response.Write(sw.ToString());
                }
            }
        }
    } 
    

    Step 3: Now go to the Controller inherit the BaseController Class. Now whenever the json method will be called it will invoke the json method of the BaseController class which will use the JsonNetResult class and hence will use JSON.NET serializer.

    Example:

    using MultipleSubmit.Models;
    using MultipleSubmit.Service;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace MultipleSubmit.Controllers
     {
        public class MultipleSubmitController : BaseController
        {
           public JsonResult Index()
            {
              var data = obj1;  // obj1 contains the Json data
    
              return Json(data, JsonRequestBehavior.AllowGet);
    
            }
        }
     }
    

    Hope it helps.....Happy Coding !

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: