Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JSON.NET as the default JSON serializer in ASP.NET MVC 3 - is it possible?

Is it possible to use JSON.NET as default JSON serializer in ASP.NET MVC 3?

According to my research, it seems that the only way to accomplish this is to extend ActionResult as JsonResult in MVC3 is not virtual...

I hoped that with ASP.NET MVC 3 that there would be a way to specify a pluggable provider for serializing to JSON.

Thoughts?

like image 321
zam6ak Avatar asked Aug 18 '11 15:08

zam6ak


People also ask

Is JSON net the same as Newtonsoft?

Thanks. Json.NET vs Newtonsoft. Json are the same thing. You must be trying to use the same code with different versions of Json.NET.

Is Newtonsoft JSON compatible with .NET core?

Text. Json library is included in the runtime for . NET Core 3.1 and later versions. For other target frameworks, install the System.

Is Newtonsoft JSON obsolete?

Yet Newtonsoft. Json was basically scrapped by Microsoft with the coming of . NET Core 3.0 in favor of its newer offering designed for better performance, System.

What is JSON serialization?

Serialization is the process of converting . NET objects such as strings into a JSON format and deserialization is the process of converting JSON data into . NET objects.


1 Answers

I believe the best way to do it, is - as described in your links - to extend ActionResult or extend JsonResult directly.

As for the method JsonResult that is not virtual on the controller that's not true, just choose the right overload. This works well:

protected override JsonResult Json(object data, string contentType, Encoding contentEncoding) 

EDIT 1: A JsonResult extension...

public class JsonNetResult : JsonResult {     public override void ExecuteResult(ControllerContext context)     {         if (context == null)             throw new ArgumentNullException("context");          var response = context.HttpContext.Response;          response.ContentType = !String.IsNullOrEmpty(ContentType)              ? ContentType              : "application/json";          if (ContentEncoding != null)             response.ContentEncoding = ContentEncoding;          // If you need special handling, you can call another form of SerializeObject below         var serializedObject = JsonConvert.SerializeObject(Data, Formatting.Indented);         response.Write(serializedObject);     } 

EDIT 2: I removed the check for Data being null as per the suggestions below. That should make newer versions of JQuery happy and seems like the sane thing to do, as the response can then be unconditionally deserialized. Be aware though, that this is not the default behavior for JSON responses from ASP.NET MVC, which rather responds with an empty string, when there's no data.

like image 147
asgerhallas Avatar answered Sep 28 '22 11:09

asgerhallas