question

ChrisRolls avatar image
0 Votes"
ChrisRolls asked LanHuang-MSFT answered

How to make MVC5 JsonResult use NewtonSoft.json CustomSerializer

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

dotnet-aspnet-mvc
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Bruce-SqlWork avatar image
0 Votes"
Bruce-SqlWork answered

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

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

LanHuang-MSFT avatar image
0 Votes"
LanHuang-MSFT answered

Hi @ChrisRolls,
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.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.