How to make MVC5 JsonResult use NewtonSoft.json CustomSerializer

ChrisRollings 6 Reputation points
2021-10-22T11:21:47.28+00:00

Hi,

I have written a custom serializer for a models property and placed the attribute above

    [JsonConverter(typeof(NewTypeConverter))]
    [TypeConverter(typeof(NewTypeIdTypeConverter<CipMakeupHistoryId>))]
    public class CipMakeupHistoryId : NewType<CipMakeupHistoryId, Guid>
    {
        public CipMakeupHistoryId(Guid value) : base(value)
        {
        }
    }

but when using with JsonResult it is not using it ?

Any help appreciated

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,254 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 55,686 Reputation points
    2021-10-24T16:06:30.53+00:00

    JsonResult does not use newtonsoft. You will need to replace it with your own code. You can define your own result type that uses newtonsoft. See thread

    https://stackoverflow.com/questions/6883204/change-default-json-serializer-used-in-asp-mvc3

    0 comments No comments

  2. Lan Huang-MSFT 25,551 Reputation points Microsoft Vendor
    2021-10-25T08:40:16.383+00:00

    Hi @ChrisRollings ,
    The built-in JsonResult cannot use Newtonsoft.Json.
    Compared with the built-in JsonResult, the advantage of using JsonNetResult is that you can get a better serializer.
    Use JSON.NET as the default JSON serializer in ASP.NET MVC.
    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.

    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);  
            }  
        }  
     }  
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments